Javascript - Get Previous Months Date

后端 未结 6 898
情深已故
情深已故 2021-02-14 12:25

If i have a variable that returns a date, in the format of dd MMM yyyy, so 28 Aug 2014, how can i get the date of the previous month.

I can modify the month via:

6条回答
  •  失恋的感觉
    2021-02-14 12:52

    var myVariable = "28 Aug 2014"
    var makeDate = new Date(myVariable);
    makeDate = new Date(makeDate.setMonth(makeDate.getMonth() - 1));
    

    Update:

    A shorter version:

    var myVariable = "28 Aug 2014"
    var makeDate = new Date(myVariable);
    
    console.log('Original date: ', makeDate.toString());
    
    makeDate.setMonth(makeDate.getMonth() - 1);
    
    console.log('After subtracting a month: ', makeDate.toString());

    Update 2:

    If you don't want to deal with corner cases just use moment.js. Native JavaScript API for Date is bad.

提交回复
热议问题