我想获取下一个星期日(JST)15:30的日期。 该怎么做?
我有一个字符串“ Sunday 15:00 JST”,我需要做的是,将其转换为最近的星期日15:00 JST周日,然后将其全部转换为Unix时代。我可能会在一周中的任何一天而不是星期日运行此代码。
答案 0 :(得分:0)
const currentDate = new Date();
// Sunday - Saturday : 0 - 6.
const currentDayOfWeek = currentDate.getDay();
// 1 - 31.
const currentDayOfMonth = currentDate.getDate();
// thursday would be: 7 - 4.
const daysUntilSunday = 7 - currentDayOfWeek;
// currentDayOfMonth + 7 would be the same day, but
// next week, then just subtract the difference between
// now and sunday.
const nextSunday = new Date().setDate(currentDayOfMonth + 7 - currentDayOfWeek);
const nextSundayAt3pm = new Date(nextSunday).setHours(15, 0, 0);
使用moment.js,您可以获取并设置星期几 https://momentjs.com/docs/#/get-set/day/
您需要做的就是创建一个新的Moment,然后将日期设置为周日。但是..
如果给出的值是0到6,则结果日期将在当前(星期日至星期六)的一周之内。
由于它将周日识别为一周的开始,因此您需要在当前周的开始时获取星期日,然后在日期前加上7天以从今天开始获取下一个星期日。
换句话说,您将天数加7。
// 0 - 6 sets it to a date of the week within the current week.
// if you provide a number greater than 6, it will bubble in to
// later weeks.
// i.e. 7 = 0 + 6 + 1. where 0 would be the previous Sunday, 6 would
// set it to Saturday of the current week, then adding an additional 1
// will set it to the Sunday of the next week.
const nextSunday = new moment(7); // sets the date to next Sunday.
// now just set the time to 3pm.
nextSunday.hour(15);