How to get yesterday's date with Momentjs?

后端 未结 8 838
清酒与你
清酒与你 2021-01-30 08:08

So, my question is simple, how do I get yesterday\'s date with MomentJs ? In Javascript it is very simple, i.e.

today = new Date();
yesterday = new Date(today.se         


        
相关标签:
8条回答
  • 2021-01-30 08:14

    Also :

    moment().subtract(1, 'day')
    

    It will give you the previous day with the same exact current time that is on your local pc.

    0 讨论(0)
  • 2021-01-30 08:17

    You can easily subtract days from moment using

    var yesterday = moment().subtract(1, 'days')

    And for finding the previous date

    var previousDay = moment('2017/11/6', 'YYYY/MM/DD').subtract(1, 'days')

    0 讨论(0)
  • 2021-01-30 08:23

    When we get yesterday's date, there are three possibilties

    1. Get yesterday date with current timing

    moment().subtract(1, 'days').toString()
    

    2. Get yesterday date with start of the day

    moment().subtract(1, 'days').startOf('day').toString()      
    

    3. Get yesterday date with end of the day

    moment().subtract(1, 'days').endOf('day').toString()
    
    0 讨论(0)
  • 2021-01-30 08:30

    This worked for me:

    var yesterday = new Date(dateInput.getTime());
    yesterday.setDate(yesterday.getDate() - 1);
    console.log(yesterday);
    
    var tomorrow = new Date(dateInput.getTime());
    tomorrow.setDate(tomorrow.getDate() + 1);
    console.log(tomorrow);
    
    dateB = moment(yesterday).format("YYYYMMDD");
    dateA = moment(tomorrow).format("YYYYMMDD");
    console.log(dateB);
    console.log(dateA);
    
    0 讨论(0)
  • 2021-01-30 08:31

    Simplest Solution

    By using moment we can easily get Yesterday, Today and Tomorrow Date

    1. Get Yesterday Date:

    moment().subtract(1, "days").format("YYYY-MM-DD");
    

    2. Get Today Date:

    moment().subtract(0, "days").format("YYYY-MM-DD");
    

    3. Get Tomorrow Date:

    moment().subtract(-1, "days").format("YYYY-MM-DD");
    
    0 讨论(0)
  • 2021-01-30 08:35

    Just like this: moment().subtract(1, 'days'). It will give you the previous day with the same exact current time that is on your local pc.

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