特定の平日の次の日付を返すにはどうすればよいですか(0〜6の数字、または日曜日から土曜日の名前のいずれかです)。
たとえば、今日、2009年10月16日金曜日 に私が渡した場合:
- 金曜日、それは今日の日付を2009年10月16日に返します
- 土曜日は2009年10月17日を返します
- 木曜日は2009年10月22日を返します
特定の平日の次の日付を返すにはどうすればよいですか(0〜6の数字、または日曜日から土曜日の名前のいずれかです)。
たとえば、今日、2009年10月16日金曜日 に私が渡した場合:
7を追加するだけでは問題は解決しません。
以下の関数は、次の曜日を提供します。
function nextDay(x){
var now = new Date();
now.setDate(now.getDate() + (x+(7-now.getDay())) % 7);
return now;
}
特定の質問に対処するためにTimの回答を少し変更したバージョンを次に示します。日付dを渡し、希望の曜日(dow 0〜6)を入力して、日付を返します。
function nextDay(d, dow){
d.setDate(d.getDate() + (dow+(7-d.getDay())) % 7);
return d;
}
これが別の簡単な解決策です
//takes dayIndex from sunday(0) to saturday(6)
function nextDate(dayIndex) {
var today = new Date();
today.setDate(today.getDate() + (dayIndex - 1 - today.getDay() + 7) % 7 + 1);
return today;
}
document.write("Next Sunday is: "+nextDate(0).toLocaleString()+"<br/>");
document.write("Next Thursday is: "+nextDate(4).toLocaleString()+"<br/>");
document.write("Next Saturday is: "+nextDate(6).toLocaleString());
ユーザー190106の回答を拡張するには、このコードで必要なものを提供する必要があります。
function getNextDay(day, resetTime){
var days = {
sunday: 0, monday: 1, tuesday: 2,
wednesday: 3, thursday: 4, friday: 5, saturday: 6
};
var dayIndex = days[day.toLowerCase()];
if (dayIndex !== undefined) {
throw new Error('"' + day + '" is not a valid input.');
}
var returnDate = new Date();
var returnDay = returnDate.getDay();
if (dayIndex !== returnDay) {
returnDate.setDate(returnDate.getDate() + (dayIndex + (7 - returnDay)) % 7);
}
if (resetTime) {
returnDate.setHours(0);
returnDate.setMinutes(0);
returnDate.setSeconds(0);
returnDate.setMilliseconds(0);
}
return returnDate;
}
alert(getNextDay('thursday', true));
また、パス番号ではなく平日名(日曜日から土曜日)で特定の平日の将来の日付を検索したい場合は、これも役立ちます。
function getDateOfWeekday(refday){
var days = {
monday: 1,
tuesday: 2,
wednesday: 3,
thursday: 4,
friday: 5,
saturday: 6,
sunday: 0
};
if(!days.hasOwnProperty(refday))throw new Error(refday+" is not listed in "+JSON.stringify(days));
var currDate = new Date();
var currTimestamp = currDate.getTime();
var triggerDay = days[refday];
var dayMillDiff=0;
var dayInMill = 1000*60*60*24;
// add a day to dayMillDiff as long as the desired refday (sunday for instance) is not reached
while(currDate.getDay()!=triggerDay){
dayMillDiff += dayInMill;
currDate = new Date(currDate.getTime()+dayInMill);
}
return new Date(currTimestamp + dayMillDiff);
}
var sunday = getDateOfWeekday("sunday");
document.write("Next Sunday is at: <strong>"+sunday.toLocaleString()+"</strong><br/>");
var thursday = getDateOfWeekday("thursday");
thursday.setHours(0,0,0,0); // set hours/minutes/seconds and millseconds to zero
document.write("Next Thursday is at: <strong>"+thursday.toLocaleString()+"</strong> on midnight<br/>");
var tuesday = getDateOfWeekday("tuesday");
document.write("Next Tuesday is at: <strong>"+tuesday.toLocaleString()+"</strong><br/>");
javascriptDateTimeプログラミング用のスイスナイフツール。