我的UNIX时间戳1411866803
相当于Sun, 28 Sep 2014 01:13:23 GMT
我想根据用户的当地时间从时间戳中获取月份。我使用以下函数:
<script>
var date = new Date(1411866803);
var month = date.getMonth();
alert(month);
</script>
这应返回9
,而不是返回0
。上面的语法有问题吗?谢谢:))
答案 0 :(得分:2)
Date对象以毫秒为单位,而UNIX时间戳使用秒。你必须把它转换过来。
var date = new Date(1411866803*1000);
var month = date.getMonth();
alert(month);
答案 1 :(得分:2)
JavaScript时间戳以毫秒表示。乘以1000:
var date = new Date(1411866803000);
var month = date.getMonth();
alert(month); // => 8
此外,月份为0,因此9月为8
,而不是9
。
答案 2 :(得分:2)
Date对象采用毫秒而不是秒。所以,只要放三个零就可以了。
var date = new Date(1411866803000);
var month = date.getMonth();
alert(month);
答案 3 :(得分:0)
如果我在控制台中测试您的脚本,我会将此日期设为:
var date = new Date(1411866803)
Date {Sat Jan 17 1970 20:11:06 GMT+1200 (NZST)}
根据该页面:http://www.w3schools.com/jsref/jsref_getmonth.asp
getMonth()方法根据当地时间返回指定日期的月份(从0到11)。
注意:1月是0,2月是1,依此类推。