Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
147
rated 0 times [  148] [ 1]  / answers: 1 / hits: 58332  / 10 Years ago, tue, october 21, 2014, 12:00:00

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:



$scope.DateMapping = function (months) {

var myVariable = 28 Aug 2014
var makeDate = new Date(myVariable);
prev = new Date(makeDate.getFullYear(), makeDate.getMonth()+1, 1);

});


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:



    var myVariable = 28 Aug 2014
var makeDate = new Date(myVariable);
var prev = new Date(makeDate.getFullYear(), makeDate.getMonth()+1, makeDate.getMonth());

console.log(myVariable)
console.log(makeDate)
console.log(prev)

Output:

28 Aug 2014
Thu Aug 28 2014 00:00:00 GMT+0100 (GMT Standard Time)
Mon Sep 01 2014 00:00:00 GMT+0100 (GMT Standard Time)


How comes although the month has incremented, the day is showing as 01 instead of 28?


More From » jquery

 Answers
8
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.


[#69055] Sunday, October 19, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mitchell

Total Points: 95
Total Questions: 110
Total Answers: 87

Location: Gabon
Member since Thu, Jul 15, 2021
3 Years ago
;