Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to substract 1 month from selected date with the right format

Tags:

javascript

I want to substract 1 month from the selected date and get it in this format mm/dd/yyyy

self.SelectedDate = "02/22/2018";
var temp = new Date(self.SelectedDate);
    temp.setDate(temp.getDate() - 30);

but the result I get is Mon Jan 08 2018 00:00:00 GMT+0800 (Malay Peninsula Standard Time)

This is just a very small part in my program so I don't want to download a library just for this. I am using AngularJS, is there a way to get what I want without downloading or adding angular filters?

like image 448
Len Avatar asked Jan 20 '26 04:01

Len


1 Answers

The Date constructor does not accept a string in this format.

self.SelectedDate = "02/22/2018";
var p = self.SelectedDate.split("/");
var temp = new Date(p[2],p[0]-1,p[1]);
    temp.setDate(temp.getDate() - 30);
const pad = n=>("0"+n).slice(-2);
var f = [pad(temp.getMonth()+1),pad(temp.getDate()),temp.getFullYear()].join("/");
console.log(f);
like image 148
I wrestled a bear once. Avatar answered Jan 21 '26 18:01

I wrestled a bear once.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!