How to get date for nearest Sunday at 15:00 JST?

js

    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

Using moment.js you can get and set the day of the week
https://momentjs.com/docs/#/get-set/day/

All you need to do is create a new Moment, then set the day to Sunday. But..

If the value given is from 0 to 6, the resulting date will be within the current (Sunday-to-Saturday) week.

Due to it recognising Sunday as the start of the week, you will need to get the Sunday at the start of the current week, then add 7 days on to the date to get the next Sunday from today.

In other words, you add 7 to the days.

    // 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);

Leave a Comment