Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
0
rated 0 times [  7] [ 7]  / answers: 1 / hits: 79272  / 10 Years ago, wed, june 4, 2014, 12:00:00

How do I get in unix timestamp of the time 1 month ago from now?



I know I need to use Date()


More From » time

 Answers
14

A simplistic answer is:


// Get a date object for the current time
var d = new Date();

// Set it to one month ago
d.setMonth(d.getMonth() - 1);

// Zero the time component
d.setHours(0, 0, 0, 0);

// Get the time value in milliseconds and convert to seconds
console.log(d/1000|0);

Note that if you subtract one month from 31 July you get 31 June, which will be converted to 1 July. similarly, 31 March will go to 31 February which will convert to 2 or 3 March depending on whether it's in a leap year or not.


So you need to check the month:


var d = new Date();
var m = d.getMonth();
d.setMonth(d.getMonth() - 1);

// If still in same month, set date to last day of
// previous month
if (d.getMonth() == m) d.setDate(0);
d.setHours(0, 0, 0, 0);

// Get the time value in milliseconds and convert to seconds
console.log(d / 1000 | 0);

Note that JavaScript time values are in milliseconds since 1970-01-01T00:00:00Z, whereas UNIX time values are in seconds since the same epoch, hence the division by 1000.


[#70720] Tuesday, June 3, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaelyn

Total Points: 619
Total Questions: 102
Total Answers: 104

Location: Honduras
Member since Sun, Dec 26, 2021
2 Years ago
;