What's the simplest way to decrement a date in Javascript by 1 day?

前端 未结 7 743
无人共我
无人共我 2020-12-17 09:30

I need to decrement a Javascript date by 1 day, so that it rolls back across months/years correctly. That is, if I have a date of \'Today\', I want to get the date for \'Ye

相关标签:
7条回答
  • 2020-12-17 09:55
    var today = new Date();
    var yesterday = new Date().setDate(today.getDate() -1);
    
    0 讨论(0)
  • 2020-12-17 09:57

    setDate(dayValue)

    dayValue is an integer from 1 to 31, representing the day of the month.

    from https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/setDate

    The behaviour solving your problem (and mine) seems to be out of specification range.

    What seems to be needed are addDate(), addMonth(), addYear() ... functions.

    0 讨论(0)
  • 2020-12-17 10:03

    var d = new Date();
    d.setDate(d.getDate() - 1);
    
    console.log(d);

    0 讨论(0)
  • 2020-12-17 10:06
     day.setDate(day.getDate() -1); //will be wrong
    

    this will return wrong day. under UTC -03:00, check for

    var d = new Date(2014,9,19);
    d.setDate(d.getDate()-1);// will return Oct 17
    

    Better use:

    var n = day.getTime();
    n -= 86400000;
    day = new Date(n); //works fine for everything
    
    0 讨论(0)
  • 2020-12-17 10:06
    origDate = new Date();
    decrementedDate = new Date(origDate.getTime() - (86400 * 1000));
    
    console.log(decrementedDate);
    
    0 讨论(0)
  • 2020-12-17 10:11

    Working with dates in JS can be a headache. So the simplest way is to use moment.js for any date operations.

    To subtract one day:

    const date = moment().subtract(1, 'day')
    
    0 讨论(0)
提交回复
热议问题