如何在JavaScript中获得时间戳?

[英]How do you get a timestamp in JavaScript?


How can I get a timestamp in JavaScript?

如何在JavaScript中获得时间戳?

Something similar to Unix's timestamp, that is, a single number that represents the current time and date. Either as a number or a string.

类似于Unix的时间戳,即表示当前时间和日期的单个数字。要么是一个数字,要么是一个字符串。

35 个解决方案

#1


3975  

var timeStampInMs = window.performance && window.performance.now && window.performance.timing && window.performance.timing.navigationStart ? window.performance.now() + window.performance.timing.navigationStart : Date.now();

console.log(timeStampInMs, Date.now());

Short & Snazzy:

短和时髦的:

+ new Date()

A unary operator like plus triggers the valueOf method in the Date object and it returns the timestamp (without any alteration).

像plus这样的一元运算符会在Date对象中触发方法的valueOf方法,它会返回时间戳(没有任何更改)。

Details:

细节:

On almost all current browsers you can use Date.now() to get the UTC timestamp in milliseconds; a notable exception to this is IE8 and earlier (see compatibility table).

在几乎所有当前的浏览器上,您都可以使用Date.now()以毫秒为单位获得UTC时间戳;一个值得注意的例外是IE8和之前的版本(参见兼容性表)。

You can easily make a shim for this, though:

不过,你可以很容易地做一个垫片。

if (!Date.now) {
    Date.now = function() { return new Date().getTime(); }
}

To get the timestamp in seconds, you can use:

为了在秒内获得时间戳,您可以使用:

Math.floor(Date.now() / 1000)

Or alternatively you could use:

或者你也可以使用:

Date.now() / 1000 | 0

Which should be slightly faster, but also less readable (also see this answer).

它应该稍微快一点,但也不太容易读(也可以看到这个答案)。

I would recommend using Date.now() (with compatibility shim). It's slightly better because it's shorter & doesn't create a new Date object. However, if you don't want a shim & maximum compatibility, you could use the "old" method to get the timestamp in milliseconds:

我建议使用日期。现在()(与兼容性shim)。它稍微好一点,因为它更短,而且不会创建新的日期对象。但是,如果您不需要shim和最大兼容性,您可以使用“旧”方法以毫秒为单位获得时间戳:

new Date().getTime()

Which you can then convert to seconds like this:

你可以把它转换成这样的几秒钟:

Math.round(new Date().getTime()/1000)

And you can also use the valueOf method which we showed above:

你也可以使用我们上面展示的方法的valueOf方法:

new Date().valueOf()

#2


417  

I like this, because it is small:

我喜欢这个,因为它很小:

+new Date

I also like this, because it is just as short and is compatible with modern browsers, and over 500 people voted that it is better:

我也喜欢这个,因为它很短而且兼容现代浏览器,超过500人投票认为它更好:

Date.now()

#3


219  

JavaScript works with the number of milliseconds since the epoch whereas most other languages work with the seconds. You could work with milliseconds but as soon as you pass a value to say PHP, the PHP native functions will probably fail. So to be sure I always use the seconds, not milliseconds.

JavaScript的工作时间是自纪元以来的毫秒数,而大多数其他的语言则以秒为单位。您可以使用毫秒,但是当您传递一个值来表示PHP时,PHP的本机函数很可能会失败。所以要确定我总是用秒,而不是毫秒。

This will give you a Unix timestamp (in seconds):

这将给您一个Unix时间戳(以秒为单位):

var unix = Math.round(+new Date()/1000);

This will give you the milliseconds since the epoch (not Unix timestamp):

这将为您提供自纪元以来的毫秒(不是Unix时间戳):

var milliseconds = new Date().getTime();

#4


123  

var time = Date.now || function() {
  return +new Date;
};

time();

#5


90  

I provide multiple solutions with descriptions in this answer. Feel free to ask questions if anything is unclear
PS: sadly someone merged this to the top answer without giving credit.

在这个答案中,我提供了多种解决方案。如果有什么不清楚的地方,请随时提问:不幸的是,有人把这个问题合并到最上面的答案,而不给予任何赞扬。


Quick and dirty solution:

快速和肮脏的解决方案:

Date.now() /1000 |0

Warning: it might break in 2038 and return negative numbers if you do the |0 magic. Use Math.floor() instead by that time

警告:如果你使用|魔法,它可能会在2038年中断并返回负数。用Math.floor()代替那个时间。

Math.floor() solution:

Math.floor()解决方案:

Math.floor(Date.now() /1000);

Some nerdy alternative by Derek 朕會功夫 taken from the comments below this answer:

一些书呆子替代德里克。朕會功夫从评论下面的回答:

new Date/1e3|0

Polyfill to get Date.now() working:

Polyfill to get data .现在()工作:

To get it working in IE you could do this (Polyfill from MDN):

为了让它在IE中工作,你可以这样做(从MDN的Polyfill):

if (!Date.now) {
    Date.now = function now() {
        return new Date().getTime();
    };
}

If you do not care about the year / day of week / daylight saving time you could strip it away and use this after 2038:

如果你不关心每周/天/日光节约时间,你可以把它带走,在2038年以后使用:

var now = (function () {
    var year = new Date(new Date().getFullYear().toString()).getTime();
    return function () {
        return Date.now() - year
    }
})();

Some output of how it will look:

它的一些输出结果如下:

new Date()
Thu Oct 29 2015 08:46:30 GMT+0100 (Mitteleuropäische Zeit )
new Date(now())
Thu Oct 29 1970 09:46:30 GMT+0100 (Mitteleuropäische Zeit )

Of course it will break daylight saving time but depending on what you are building this might be useful to you if you need to do binary operations on timestamps after int32 will break in 2038.

当然,它会破坏日光节约时间,但取决于你所构建的内容,如果你需要在2038年int32之后的时间戳中进行二进制操作,这可能对你有用。

This will also return negative values but only if the user of that PC you are running your code on is changing their PC's clock at least to 31th of december of the previous year.

这也会返回负值,但前提是你正在运行你的代码的那台电脑的用户正在改变他们的电脑时钟,至少在前一年的12月31日。


If you just want to know the relative time from the point of when the code was run through first you could use something like this:

如果你只是想知道从代码运行到第一步的相对时间你可以使用如下的东西:

var relativeTime = (function () {
    var start = Date.now();
    return function () {
        return Date.now() - start
    }
})();

In case you are using jQuery you could use $.now() as described in jQuery's Docs which makes the polyfill obsolete since $.now() internally does the same thing: (new Date).getTime()

如果您使用的是jQuery,那么您可以使用$.now(),如jQuery文档中所描述的那样,从$.now()开始,就会使polyfill过时。

If you are just happy about jQuery's version consider upvoting this answer since I did not find it myself.

如果你对jQuery的版本感到满意,考虑一下这个答案,因为我自己没有找到。


Now a tiny explaination of what |0 does:

现在对|0的解释是:

By providing |, you tell the interpreter to do a binary OR operation. Bit operations require absolute numbers which turns the decimal result from Date.now() / 1000 into an integer.

通过提供|,您可以告诉解释器执行二进制或操作。位操作需要绝对数字,它将数据的十进制结果转化为整数。

During that conversion, decimals are removed, resulting in the same result as using Math.floor() but using less code.

在转换过程中,删除小数,结果与使用Math.floor()的结果相同,但使用的代码更少。

Be warned though: it will convert a 64 bit double to a 32 bit integer. This will result in information loss when dealing with huge numbers. Timestamps will break after 2038 due to 32 bit integer overflow.

请注意:它将把64位的双精度转换为32位整数。这将导致在处理大量数据时信息丢失。由于32位整数溢出,时间戳将在2038年后中断。


For further information about Date.now follow this link: Date.now() @ MDN

有关日期的进一步信息。现在按照这个链接:Date.now() @ MDN。

#6


65  

var timestamp = Number(new Date()); // current time as number

#7


48  

jQuery provides its own method to get the timestamp:

jQuery提供了自己的方法来获得时间戳:

var timestamp = $.now();

(besides it just implements (new Date).getTime() expression)

(而且它只是实现了(new Date).getTime()表达式)

REF: http://api.jquery.com/jQuery.now/

裁判:http://api.jquery.com/jQuery.now/

#8


35  

Just to add up, here's a function to return a timestamp string in Javascript. Example: 15:06:38 PM

这里有一个函数,用于返回Javascript中的时间戳字符串。例如:15:06:38点

function displayTime() {
    var str = "";

    var currentTime = new Date()
    var hours = currentTime.getHours()
    var minutes = currentTime.getMinutes()
    var seconds = currentTime.getSeconds()

    if (minutes < 10) {
        minutes = "0" + minutes
    }
    if (seconds < 10) {
        seconds = "0" + seconds
    }
    str += hours + ":" + minutes + ":" + seconds + " ";
    if(hours > 11){
        str += "PM"
    } else {
        str += "AM"
    }
    return str;
}

#9


32  

console.log(new Date().valueOf()); // returns the number of milliseconds since the epoch

#10


24  

In addition to the other options, if you want a dateformat ISO, you get can get it directly

除了其他选项,如果您想要一个dateformat ISO,您可以直接得到它。

console.log(new Date().toISOString());

#11


19  

The Date.getTime() method can be used with a little tweak:

gettime()方法可以稍微调整一下:

The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00 UTC.

getTime方法返回的值是自1970年1月1日00:00:00 UTC以来的毫秒数。

Divide the result by 1000 to get the Unix timestamp, floor if necessary:

将结果除以1000,以获得Unix时间戳,如有必要,可以在地板上使用:

(new Date).getTime() / 1000

The Date.valueOf() method is functionally equivalent to Date.getTime(), which makes it possible to use arithmetic operators on date object to achieve identical results. In my opinion, this approach affects readability.

valueof()方法在功能上等价于Date.getTime(),这使得在date对象上使用算术运算符实现相同的结果成为可能。在我看来,这种方法影响可读性。

#12


19  

One I haven't seen yet

我还没见过。

Math.floor(Date.now() / 1000); // current time in seconds

Another one I haven't seen yet is

还有一个我还没见过的。

var _ = require('lodash'); // from here https://lodash.com/docs#now
_.now();

#13


15  

Here is a simple function to generate timestamp in the format: mm/dd/yy hh:mi:ss

这里有一个简单的函数来生成时间戳的格式: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())));
}

#14


15  

The code Math.floor(new Date().getTime() / 1000) can be shortened to new Date / 1E3 | 0.

数学的代码。新日期(). gettime() / 1000)可以缩写为new Date / 1E3 | 0。

Consider to skip direct getTime() invocation and use | 0 as a replacement for Math.floor() function. It's also good to remember 1E3 is a shorter equivalent for 1000 (uppercase E is preferred than lowercase to indicate 1E3 as a constant).

考虑跳过直接getTime()调用,并使用| 0作为Math.floor()函数的替换。记住1E3是一个更短的等价于1000(大写的E比小写的E表示1E3是一个常量)也是好的。

As a result you get the following:

因此,你得到以下信息:

var ts = new Date / 1E3 | 0;

console.log(ts);

#15


14  

// The Current Unix Timestamp
// 1443534720 seconds since Jan 01 1970. (UTC)

// seconds
console.log(Math.floor(new Date().valueOf() / 1000)); // 1443534720
console.log(Math.floor(Date.now() / 1000)); // 1443534720
console.log(Math.floor(new Date().getTime() / 1000)); // 1443534720

// milliseconds
console.log(Math.floor(new Date().valueOf())); // 1443534720087
console.log(Math.floor(Date.now())); // 1443534720087
console.log(Math.floor(new Date().getTime())); // 1443534720087

// jQuery
// seconds
console.log(Math.floor($.now() / 1000)); // 1443534720
// milliseconds
console.log($.now()); // 1443534720087
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

#16


12  

I highly recommend using moment.js. To get the number of milliseconds since UNIX epoch, do

我强烈推荐使用moment.js。要获得自UNIX时代以来的毫秒数,请执行。

moment().valueOf()

To get the number of seconds since UNIX epoch, do

要获得自UNIX时代以来的秒数,请执行。

moment().unix()

You can also convert times like so:

你也可以这样转换时间:

moment('2015-07-12 14:59:23', 'YYYY-MM-DD HH:mm:ss').valueOf()

I do that all the time. No pun intended.

我一直都这么做。没有双关。

To use moment.js in the browser:

使用的时刻。js的浏览器:

<script src="moment.js"></script>
<script>
    moment().valueOf();
</script>

For more details, including other ways of installing and using MomentJS, see their docs

有关更多细节,包括安装和使用MomentJS的其他方法,请参阅他们的文档。

#17


12  

You can only use

你只能使用

    var timestamp = new Date().getTime();
    console.log(timestamp);

to get the current timestamp. No need to do anything extra.

获取当前时间戳。不需要做任何额外的事情。

#18


12  

Date native object in JavaScript is the way we get all data about time.

在JavaScript中,Date native对象是我们获取所有时间数据的方式。

Just be careful in JavaScript the timestamp is depends on the client computer setting, so it's not 100% accurate timestamp. For getting the best result, you need to get the timestamp from the server-side.

在JavaScript中要小心,时间戳取决于客户端计算机设置,所以它不是100%准确的时间戳。为了获得最好的结果,您需要从服务器端获得时间戳。

Anyway, my preferred way is using vanilla. This is a common way of doing it in JavaScript:

不管怎样,我最喜欢香草冰淇淋。这是在JavaScript中常用的方法:

Date.now(); //return 1495255666921

In MDN it's mentioned as below:

在MDN中,它被提到如下:

The Date.now() method returns the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.
Because now() is a static method of Date, you always use it as Date.now().

现在()方法返回自1970年1月1日以来的毫秒数。因为now()是日期的静态方法,所以您总是使用它作为日期。

If you using a version below ES5, Date.now(); not works and you need to use:

如果您使用的是ES5以下的版本,那么现在();不工作,你需要使用:

new Date().getTime();

#19


11  

For a timestamp with microsecond resolution, there's performance.now:

对于一个具有微秒分辨率的时间戳来说,现在有了性能。

function time() { 
  return performance.now() + performance.timing.navigationStart;
}

This could for example yield 1436140826653.139, while Date.now only gives 1436140826653.

例如,这可能会产生1436140826653.139,而日期。现在只给了1436140826653。

#20


10  

Any browsers not supported Date.now, you can use this for get current date time:

任何浏览器都不支持日期。现在,你可以用这个来获得当前的日期时间:

currentTime = Date.now() || +new Date()

#21


9  

This one has a solution : which converts unixtime stamp to tim in js try this

这个有一个解决方案:将unixtime的stamp转换成js中的tim。

var a = new Date(UNIX_timestamp*1000);
var hour = a.getUTCHours();
var min = a.getUTCMinutes();
var sec = a.getUTCSeconds();

#22


8  

I learned a really cool way of converting a given Date object to a Unix timestamp from the source code of JQuery Cookie the other day.

我学习了一种很酷的方法,可以将给定的日期对象从JQuery Cookie的源代码中转换为Unix时间戳。

Here's an example:

这里有一个例子:

var date = new Date();
var timestamp = +date;

#23


8  

If want a basic way to generate a timestamp in Node.js this works well.

如果需要在节点中生成时间戳的基本方法。js这工作得很好。

var time = process.hrtime();
var timestamp = Math.round( time[ 0 ] * 1e3 + time[ 1 ] / 1e6 );

Our team is using this to bust cache in a localhost environment. The output is /dist/css/global.css?v=245521377 where 245521377 is the timestamp generated by hrtime().

我们的团队正在使用它在本地主机环境中进行缓存。输出/ dist / css / global.css吗?其中245521377是由hrtime()生成的时间戳。

Hopefully this helps, the methods above can work as well but I found this to be the simplest approach for our needs in Node.js.

希望这能有所帮助,上面的方法也能起作用,但我发现这是Node.js中最简单的方法。

#24


7  

For lodash and underscore users, use _.now.

对于lodash和下划线用户,请使用_.now。

var timestamp = _.now(); // in milliseconds

#25


7  

This seems to work.

这似乎工作。

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);
            }
};

#26


5  

Moment.js can abstract away a lot of the pain in dealing with Javascript Dates.

的时刻。js可以在处理Javascript日期时去掉很多痛苦。

See: http://momentjs.com/docs/#/displaying/unix-timestamp/

参见:http://momentjs.com/docs/ /显示/ unix时间戳

moment().unix();

#27


4  

more simpler way:

更简单的方法:

var timeStamp=event.timestamp || new Date().getTime();

#28


3  

sometime I need it in objects for xmlhttp calls, so I do like this.

有时我需要它在xmlhttp调用的对象中,所以我这样做。

timestamp : parseInt(new Date().getTime()/1000, 10)

#29


3  

The advised, proper way is Number(new Date()), in terms of code- readability,

建议的正确的方法是数字(new Date()),在代码可读性方面,

Also, UglifyJS and Google-Closure-Compiler will lower the complexity of the parsed code-logic-tree (relevant if you are using one of them to obscure/minify your code).

此外,UglifyJS和google - closure -编译器将降低解析的代码逻辑树的复杂性(如果您使用其中之一来模糊/缩小您的代码的话)。

for Unix timestamp, which has a lower time resolution, just divide current number with 1000, keeping the whole.

对于具有较低时间分辨率的Unix时间戳,只需将当前数字与1000进行分割,保持完整。

#30


3  

As of writing this, the top answer is 9 years old, and a lot has changed since then - not least, we have near universal support for a non-hacky solution:

在写这篇文章的时候,最上面的答案是9岁,从那以后,情况发生了很大的变化——尤其是,我们几乎普遍支持一个非hacky的解决方案:

Date.now()

If you want to be absolutely certain that this won't break in some ancient (pre ie9) browser, you can put it behind a check, like so:

如果你想绝对肯定这不会在某些古老的浏览器中出现,你可以把它放在一张支票后面,就像这样:

const currentTimestamp = (!Date.now ? +new Date() : Date.now());

This will return the milliseconds since epoch time, of course, not seconds.

这将返回自纪元以来的毫秒数,当然不是秒。

MDN Documentation on Date.now

MDN Date.now文档

智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2008/10/21/fd2ead67b130ab935a3d219cb9fec695.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告