我想要一个表示当前日期和时间的数字,比如Unix时间戳。
当前回答
time = Math.round(((new Date()).getTime()-Date.UTC(1970,0,1))/1000);
其他回答
我在这个答案中提供了多种解决方案和描述。如果有任何不清楚的地方,请随时提问
快速和肮脏的解决方案:
Date.now() /1000 |0
警告:如果您使用|0魔法,它可能会在2038年中断并返回负数。此时改用Math.floor()
Math.floor()解决方案:
Math.floor(Date.now() /1000);
德里克的书呆子替代品朕會功夫 摘自以下评论:
new Date/1e3|0
Polyfill以获取Date.now()工作:
要使其在IE中工作,您可以执行以下操作(MDN的Polyfill):
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
如果您不关心年份/星期几/夏时制,您需要记住2038年之后的日期:
按位操作将导致使用32位整数而不是64位浮点。
您需要将其正确使用为:
Math.floor(Date.now() / 1000)
如果您只想知道从代码第一次运行时起的相对时间,可以使用以下内容:
const relativeTime = (() => {
const start = Date.now();
return () => Date.now() - start;
})();
在使用jQuery的情况下,可以使用$.now(),如jQuery的Docs中所述,这会使polyfill过时,因为$.now()在内部执行相同的操作:(newDate).getTime()
如果您对jQuery的版本感到满意,请考虑放弃这个答案,因为我自己没有找到它。
现在对|0的作用做一个小小的解释:
通过提供|,您可以告诉解释器执行二进制OR运算。位操作需要将Date.now()/1000的十进制结果转换为整数的绝对数。
在转换过程中,小数被删除,结果与使用Math.floor()输出的结果类似。
不过,请注意:它会将64位的双精度转换为32位的整数。这将导致处理大量数据时信息丢失。2038年后,由于32位整数溢出,时间戳将中断,除非Javascript在严格模式下移动到64位整数。
有关Date.now的更多信息,请点击以下链接:Date.now()@MDN
我强烈建议使用moment.js
moment().valueOf()
要获取自UNIX纪元以来的秒数,请执行
moment().unix()
也可以这样转换时间:
moment('2015-07-12 14:59:23', 'YYYY-MM-DD HH:mm:ss').valueOf()
我一直这么做。没有双关语。
要在浏览器中使用moment.js:
<script src="moment.js"></script>
<script>
moment().valueOf();
</script>
有关更多详细信息,包括安装和使用MomentJS的其他方式,请参阅他们的文档
下面是一个生成时间戳的简单函数,格式为:mm/dd/yy hh:mi:ss
function getTimeStamp() {
var now = new Date();
return ((now.getMonth() + 1) + '/' +
(now.getDate()) + '/' +
now.getFullYear() + " " +
now.getHours() + ':' +
((now.getMinutes() < 10)
? ("0" + now.getMinutes())
: (now.getMinutes())) + ':' +
((now.getSeconds() < 10)
? ("0" + now.getSeconds())
: (now.getSeconds())));
}
这似乎奏效了。
console.log(clock.now);
// returns 1444356078076
console.log(clock.format(clock.now));
//returns 10/8/2015 21:02:16
console.log(clock.format(clock.now + clock.add(10, 'minutes')));
//returns 10/8/2015 21:08:18
var clock = {
now:Date.now(),
add:function (qty, units) {
switch(units.toLowerCase()) {
case 'weeks' : val = qty * 1000 * 60 * 60 * 24 * 7; break;
case 'days' : val = qty * 1000 * 60 * 60 * 24; break;
case 'hours' : val = qty * 1000 * 60 * 60; break;
case 'minutes' : val = qty * 1000 * 60; break;
case 'seconds' : val = qty * 1000; break;
default : val = undefined; break;
}
return val;
},
format:function (timestamp){
var date = new Date(timestamp);
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var seconds = "0" + date.getSeconds();
// Will display time in xx/xx/xxxx 00:00:00 format
return formattedTime = month + '/' +
day + '/' +
year + ' ' +
hours + ':' +
minutes.substr(-2) +
':' + seconds.substr(-2);
}
};
我还没见过
Math.floor(Date.now() / 1000); // current time in seconds
另一个我还没看到的是
var _ = require('lodash'); // from here https://lodash.com/docs#now
_.now();