Getting the date of next Monday

前端 未结 9 454
臣服心动
臣服心动 2020-12-02 23:06

How can I get the next Monday in JavaScript? I can\'t find anything of this in the internet and I have also tried a lot of codes and understanding of this but I can\'t reall

相关标签:
9条回答
  • 2020-12-02 23:24

    This will do:

    var d = new Date();
    d.setDate(d.getDate() + (1 + 7 - d.getDay()) % 7);
    console.log(d);
    
    0 讨论(0)
  • 2020-12-02 23:31

    If you need to handle time zones, one option would be to use the UTCDate methods setUTCDate() and getUTCDate(). This allows for consistency so the calculation is the same no matter the time zone setting.

    var d = new Date();
    d.setUTCDate(d.getUTCDate() + (7 - d.getUTCDay()) % 7 + 1);
    

    (This is the example from above where on a Monday the following Monday is returned)

    0 讨论(0)
  • 2020-12-02 23:31

    Please try this

    d = new Date(d);
    var day = d.getDay(),
    diff = d.getDate() - day + (day == 0 ? -6:1);
    alert(new Date(d.setDate(diff)));
    
    0 讨论(0)
  • 2020-12-02 23:31

    This is my solution

    var days =[1,7,6,5,4,3,2];
    var d = new Date();
    d.setDate(d.getDate()+days[d.getDay()]);
    console.log(d);

    0 讨论(0)
  • 2020-12-02 23:32
    var closestMonday = () => {
        var curr_date = new Date(); // current date
        var day_info = 8.64e+7; // milliseconds per day
        var days_to_monday = 8 - curr_date.getDay(); // days left to closest Monday
        var monday_in_sec = curr_date.getTime() + days_to_monday * day_info; // aleary Monday in seconds from 1970 
        var next_monday = new Date(monday_in_sec); // Monday in date object
        next_monday.setHours(0,0,0);
        return next_monday;
    }
    
    0 讨论(0)
  • 2020-12-02 23:35

    Using moment.js,

    moment().add(7, 'days').calendar();
    
    0 讨论(0)
提交回复
热议问题