Javascript获取1个月前的时间戳

Har*_*rry 23 javascript time

我怎样才能获得1个月前的unix时间戳?

我知道我需要使用 Date()

Rob*_*obG 35

一个简单的答案是:

// 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 hours
d.setHours(0, 0, 0);

// Zero the milliseconds
d.setMilliseconds(0);

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

请注意,如果您从7月31日开始减去一个月,您将获得6月31日,这将转换为7月1日.同样,3月31日将到2月31日,根据是否处于闰年,将转换为3月2日或3日.

所以你需要查看月份:

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);
d.setMilliseconds(0);

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

请注意,自1970-01-01T00:00:00Z以来,JavaScript时间值以毫秒为单位,而UNIX时间值以相同纪元以来的秒数为单位,因此除以1000.

  • 对于任何想知道的人,是的,你可以为负值做一个d.setMonth(在1月的情况下).令我惊喜的是,这个代码示例在这种情况下仍能正常工作. (4认同)

NRa*_*Raf 15

你可以看看Moment.JS.它有一堆有用的日期相关方法.

你可以这样做:

moment().subtract('months', 1).unix()
Run Code Online (Sandbox Code Playgroud)


Mr.*_*oco 10

var d = new Date();
Run Code Online (Sandbox Code Playgroud)

并将月份设置为一个月前.(编者)

d.setMonth(d.getMonth()-1);
Run Code Online (Sandbox Code Playgroud)