How to get “the day before a date” in javascript?

后端 未结 3 1307
野性不改
野性不改 2020-12-29 05:39

These two stack overflow questions ask a similar question, but their solution doesn\'t seem to work for me: Javascript Yesterday Javascript code for showing yesterday's

相关标签:
3条回答
  • 2020-12-29 05:50
    var allmonths = [
        '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'
    ];
    var alldates = [
        '01', '02', '03', '04', '05', '06', '07', '08', '09', '10',
        '11', '12', '13', '14', '15', '16', '17', '18', '19', '20',
        '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'
    ];
    
    var today = "2014-12-25";   
    var aDayBefore = new Date(today);
    aDayBefore.setDate(aDayBefore.getDate() - 1);
    
    document.write(aDayBefore.getFullYear() 
      + '-' + allmonths[aDayBefore.getMonth()] 
      + '-' + alldates[aDayBefore.getDate() - 1]);
    
    0 讨论(0)
  • 2020-12-29 06:02

    Try this:

    var date = new Date('04/28/2013 00:00:00');
    var yesterday = new Date(date.getTime() - 24*60*60*1000);
    
    0 讨论(0)
  • 2020-12-29 06:12

    You're making a whole new date.

    var yesterday = new Date(date.getTime());
    yesterday.setDate(date.getDate() - 1);
    

    That'll make you a copy of the first date. When you call setDate(), it just affects the day-of-the-month, not the whole thing. If you start with a copy of the original date, and then set the day of the month back, you'll get the right answer.

    0 讨论(0)
提交回复
热议问题