返回一个月,我有一个UNIX时间戳1411866803
这相当于Sun, 28 Sep 2014 01:13:23 GMT
的Javascript不能从UNIX时间戳
我想根据用户的本地时间与时间戳获得一个月。我用下面的功能:
<script>
var date = new Date(1411866803);
var month = date.getMonth();
alert(month);
</script>
这应返回9
而是返回0
。上述语法有问题吗?谢谢:)
返回一个月,我有一个UNIX时间戳1411866803
这相当于Sun, 28 Sep 2014 01:13:23 GMT
的Javascript不能从UNIX时间戳
我想根据用户的本地时间与时间戳获得一个月。我用下面的功能:
<script>
var date = new Date(1411866803);
var month = date.getMonth();
alert(month);
</script>
这应返回9
而是返回0
。上述语法有问题吗?谢谢:)
JavaScript的时间戳以毫秒为单位。乘以1000:
var date = new Date(1411866803000);
var month = date.getMonth();
alert(month); // => 8
此外,月份是基于0的,所以九月份是8
,不9
。
Date对象以毫秒为单位,而UNIX时间戳则使用秒。你必须将其转换。
var date = new Date(1411866803*1000);
var month = date.getMonth();
alert(month);
如果我在一个控制台测试你的脚本,我得到这个日期是:
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,依此类推。
Date对象以秒为单位而不是秒。所以,只需投入三个零,你就会好起来的。
var date = new Date(1411866803000);
var month = date.getMonth();
alert(month);