【问题标题】:Javascript get timestamp of 1 month ago [duplicate]Javascript获取1个月前的时间戳[重复]
【发布时间】:2014-07-25 19:05:44
【问题描述】:

如何获取从现在开始 1 个月前的时间的 unix 时间戳?

我知道我需要使用Date()

【问题讨论】:

标签: javascript time


【解决方案1】:

一个简单的答案是:

// 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 日减去 1 个月,则会得到 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);

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

【讨论】:

  • 对于任何想知道的人,是的,您可以为负值执行 d.setMonth(在 1 月的情况下)。我很惊喜,这个代码示例在这种情况下仍然有效。
  • 如果是 1 月,如何将月份设为 12。我的月份是 11
  • @NehalJaisalmeria——我不明白你的问题。对于 1 月,getMonth 返回 0。减去 1 得到 -1,setMonth 将其转换为上一年的 12 月,即 ECMAScript 的第 11 个月。请参阅 getMonth in javascript gives previous month
【解决方案2】:
var d = new Date();

并将月份设置为前一个月。 (已编辑)

d.setMonth(d.getMonth()-1);

【讨论】:

  • 你是对的。我的错。
【解决方案3】:

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

你可以这样做:

moment().subtract('months', 1).unix()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-18
    • 2013-11-06
    • 2013-07-26
    • 1970-01-01
    • 1970-01-01
    • 2012-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多