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:
JavaScript
x
8
1
$scope.DateMapping = function (months) {
2
3
var myVariable = "28 Aug 2014"
4
var makeDate = new Date(myVariable);
5
prev = new Date(makeDate.getFullYear(), makeDate.getMonth()+1, 1);
6
7
});
8
Essentially, this is adding one to the Month.. But how can i account for years, so if the current date is 12 Dec 2014, the previous would be 12 Jan 2013?
My application is using AngularJS can make use of filters.
UPDATE:
JavaScript
1
14
14
1
var myVariable = "28 Aug 2014"
2
var makeDate = new Date(myVariable);
3
var prev = new Date(makeDate.getFullYear(), makeDate.getMonth()+1, makeDate.getMonth());
4
5
console.log(myVariable)
6
console.log(makeDate)
7
console.log(prev)
8
9
Output:
10
11
28 Aug 2014
12
Thu Aug 28 2014 00:00:00 GMT+0100 (GMT Standard Time)
13
Mon Sep 01 2014 00:00:00 GMT+0100 (GMT Standard Time)
14
How comes although the month has incremented, the day is showing as 01 instead of 28?
Advertisement
Answer
JavaScript
1
4
1
var myVariable = "28 Aug 2014"
2
var makeDate = new Date(myVariable);
3
makeDate = new Date(makeDate.setMonth(makeDate.getMonth() - 1));
4
Update:
A shorter version:
JavaScript
1
8
1
var myVariable = "28 Aug 2014"
2
var makeDate = new Date(myVariable);
3
4
console.log('Original date: ', makeDate.toString());
5
6
makeDate.setMonth(makeDate.getMonth() - 1);
7
8
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.