Javascript获取1个月前的时间戳

Javascript获取1个月前的时间戳,javascript,time,Javascript,Time,从现在起,如何输入1个月前的unix时间戳 我知道我需要使用Date()。它有一系列有用的与日期相关的方法 你可以做: moment().subtract('months', 1).unix() 并将月份设置为前一个月。(编辑) 一个简单的答案是: // Get a date object for the current time var d = new Date(); // Set it to one month ago d.setMonth(d.getMonth() - 1); //

从现在起,如何输入1个月前的unix时间戳


我知道我需要使用
Date()。它有一系列有用的与日期相关的方法

你可以做:

moment().subtract('months', 1).unix()
并将月份设置为前一个月。(编辑)


一个简单的答案是:

// 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);
注意,如果你从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, 0);

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

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

你说的“一个月前”是什么意思?相当于30天前的时间?上个月的同一天?如果是后者,上个月<31天时如何处理第31天?一旦你弄清楚你想要什么,它应该很容易就能工作;dt.setMonth(dt.getMonth()-1)查看dup。使用
x=-1
。你是对的。我的错。对于任何想知道,是的,你可以做一个d.setMonth为负值(在一月的情况下)。我惊喜地发现,这个代码示例在这种情况下仍然有效。在1月份的情况下,如何将月份设置为12。我将得到一个月的薪水11@NehalJaisalmeria-我不明白你的问题。对于一月,getMonth返回0。减去1得到-1,setMonth将其转换为上一年的12月,即ECMAScript第11个月。看见
// 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);
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);