我想要一个表示当前日期和时间的数字,比如Unix时间戳。
当前回答
下面是另一个在JavaScript中生成时间戳的解决方案-包括单个数字的填充方法-在结果中使用天、月、年、小时、分钟和秒(jsfiddle的工作示例):
var pad = function(int) { return int < 10 ? 0 + int : int; };
var timestamp = new Date();
timestamp.day = [
pad(timestamp.getDate()),
pad(timestamp.getMonth() + 1), // getMonth() returns 0 to 11.
timestamp.getFullYear()
];
timestamp.time = [
pad(timestamp.getHours()),
pad(timestamp.getMinutes()),
pad(timestamp.getSeconds())
];
timestamp.now = parseInt(timestamp.day.join("") + timestamp.time.join(""));
alert(timestamp.now);
其他回答
在写这篇文章时,最重要的答案是9年前的事了,从那以后发生了很多变化——最重要的是,我们几乎得到了对非黑客解决方案的普遍支持:
Date.now()
如果你想绝对肯定这不会在某些古老的(ie9之前的)浏览器中出现,你可以将其置于检查之后,如下所示:
const currentTimestamp = (!Date.now ? +new Date() : Date.now());
当然,这将返回自纪元时间以来的毫秒,而不是秒。
Date.now上的MDN文档
对于微秒分辨率的时间戳,有性能。现在:
function time() {
return performance.now() + performance.timing.navigationStart;
}
例如,这可能产生1436140826653.139,而Date.now仅产生143614086653。
var my_timestamp=~~(Date.now()/1000);
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())));
}
JavaScript的工作时间是从纪元开始的毫秒数,而大多数其他语言的工作时间都是秒。您可以使用毫秒来工作,但只要您传递一个值来表示PHP,PHP本机函数可能就会失败。所以,为了确保我总是使用秒,而不是毫秒。
这将为您提供Unix时间戳(以秒为单位):
var unix = Math.round(+new Date()/1000);
这将为您提供自纪元以来的毫秒数(而不是Unix时间戳):
var milliseconds = new Date().getTime();