50

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

I know I need to use Date()

Harry
  • 52,711
  • 71
  • 177
  • 261

3 Answers3

71

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.

RobG
  • 142,382
  • 31
  • 172
  • 209
  • 9
    For anyone wondering, yes, you can do a d.setMonth for a negative value (in the case of January). I was pleasantly surprised that worked and this code sample still works in that case. – ryanm Dec 07 '15 at 19:50
  • How to get month as 12 in case of January. I am getting month as 11 – Nehal Jaisalmeria Jan 28 '21 at 11:21
  • 1
    @NehalJaisalmeria—I don't understand your issue. For January, *getMonth* returns 0. Subtracting 1 gives -1, *setMonth* converts that to December the previous year, which is ECMAScript month 11. See [*getMonth in javascript gives previous month*](https://stackoverflow.com/questions/18624326/getmonth-in-javascript-gives-previous-month). – RobG Jan 28 '21 at 23:44
  • On the 31st of May 2023 (today), I run d.setMonth(d.getMonth() - 1); and get May 1st 2023 ? – Fiach Reid May 31 '23 at 11:28
  • @FiachReid—yes, because 31 May less one month goes to 31 April, which doesn't exist, so it rolls over to 1 May. See [*JavaScript function to add X months to a date*](https://stackoverflow.com/questions/2706125/javascript-function-to-add-x-months-to-a-date). – RobG Jun 08 '23 at 12:17
24
var d = new Date();

And set the month to a month before. (EDITED)

d.setMonth(d.getMonth()-1);
Mr.Cocococo
  • 1,401
  • 2
  • 11
  • 13
20

You could take a look at Moment.JS. It has a bunch of useful date related methods.

You could do:

moment().subtract('months', 1).unix()
NRaf
  • 7,407
  • 13
  • 52
  • 91