Javascript jQuery/JS - 如何比较两个日期/时间戳?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5174952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:56:37  来源:igfitidea点击:

jQuery/JS - How to compare two date/time stamps?

javascriptjquery

提问by AnApprentice

I have two date/time stamps:

我有两个日期/时间戳:

d1 = 2011-03-02T15:30:18-08:00 
d2 = 2011-03-02T15:36:05-08:00

I want to be above to compare the two:

我想在上面比较两者:

if (new Date(d1) < new Date(d2)) {alert('newer')}

But that does not appear to be working correctly. Is there a way to compare not just the dates but the times as well.? thanks

但这似乎不能正常工作。有没有办法不仅可以比较日期,还可以比较时间。?谢谢

UPDATE:

更新:

console.log(d1 + ' ' + d2);
console.log(new Date(d1) > new Date(d2))


2011-03-02T15:30:18-08:00 2011-03-02T15:36:05-08:00
false
2011-03-02T15:30:18-08:00 2011-03-02T15:30:18-08:00
false
2011-03-02T15:30:18-08:00 2011-03-02T14:15:04-08:00
false

回答by user113716

Your timestamps should be strings.

您的时间戳应该是字符串。

var d1 = "2011-03-02T15:30:18-08:00";
var d2 = "2011-03-02T15:36:05-08:00";

if (new Date(d1) < new Date(d2)) {alert('newer')}

Example:http://jsfiddle.net/hKPkF/

示例:http : //jsfiddle.net/hKPkF/

回答by madsj

You may be having trouble with the date string format. I am getting Invalid date if I do:

您可能在日期字符串格式方面遇到问题。如果我这样做,我会收到无效日期:

new Date("2011-03-02T15:30:18-08:00");

Here's what works for me on Chrome:

以下是在 Chrome 上对我有用的内容:

var d1 = "Thu Mar 03 2011 00:53:54 GMT+0100 (CET)";
var d2 = "Thu Mar 03 2011 03:53:54 GMT+0100 (CET)";

if (new Date(d1) < new Date(d2)) {console.log('newer')}

If you are working in ruby on the server side, you could convert to UTC from a Timeobject. Here it is, with a little massaging to convert to a format that is identical to javascript's Date object toUTCStringmethod:

如果您在服务器端使用 ruby​​,则可以从Time对象转换为 UTC 。在这里,只需稍加按摩即可转换为与 javascript 的 Date 对象toUTCString方法相同的格式:

tm = Time.new
utc_tm = tm.getutc
utc_tm.strftime("%a, %d %b %Y %H:%M:%S GMT")

Output: "Thu, 03 Mar 2011 00:46:55 GMT"

输出: "Thu, 03 Mar 2011 00:46:55 GMT"

回答by Jeff B

Seems to work fine for me, although you have to format correctly (i.e. semicolons, quotes):

对我来说似乎工作正常,尽管您必须正确格式化(即分号、引号):

var d1 = "2011-03-02T15:30:18-08:00";
var d2 = "2011-03-02T15:36:05-08:00";

if(new Date(d1) < new Date(d2)) {alert('newer')};

And yes, it takes time into account. If you do this:

是的,这需要考虑时间。如果你这样做:

alert(new Date(d1) - new Date(d2));

You get 347000, which is 347 seconds, or 5 minutes, 47 seconds. This is the correct difference between the two.

你得到 347000,即 347 秒,或 5 分 47 秒。这是两者之间的正确区别。

回答by kennebec

var d1= '2011-03-02T15:30:18-08:00', d2= '2011-03-02T15:36:05-08:00'; Some browsers can convert an ISO string to a Date, with new Date or Date.parse.

var d1='2011-03-02T15:30:18-08:00', d2='2011-03-02T15:36:05-08:00'; 一些浏览器可以将 ISO 字符串转换为日期,使用 new Date 或 Date.parse。

A lot of browsers in use today cannot-you may need to write your own conversion.

今天使用的许多浏览器都不能-您可能需要编写自己的转换。

This one seems to work, but it'll need refining. I added a shim for browsers that don't have an array.map, based on mozilla org's public code.

这个似乎有效,但需要改进。我为没有 array.map 的浏览器添加了一个 shim,基于 mozilla org 的公共代码。

Date.fromISO= function(s){
    var day, tz, 
    rx=  /^(\d{4}\-\d\d\-\d\d([tT][\d:\.]*)?)([zZ]|([+\-])(\d\d):(\d\d))?$/, 
    p= rx.exec(s) || [];
    if(p[1]){
        day= p[1].split(/\D/).map(function(itm){
            return parseInt(itm, 10) || 0;
        });
        day[1]-= 1;
        day= new Date(Date.UTC.apply(Date, day));
        if(!day.getDate()) return NaN;
        if(p[5]){
            tz= parseInt(p[5], 10)*60;
            if(p[6]) tz += parseInt(p[6], 10);
            if(p[4]== "+") tz*= -1;
            if(tz) day.setUTCMinutes(day.getUTCMinutes()+ tz);
        }
        return day;
    }
    return NaN;
}
Array.prototype.map= Array.prototype.map || function(fun, scope){
    var L= this.length, A= [], i= 0;
    if(typeof fun== 'function'){
        while(i< L){
            if(i in this) A[i]= fun.call(scope, this[i], i, this);
            ++i;
        }
        return A;
    }
}
var d1= '2011-03-02T15:30:18-08:00', d2= '2011-03-02T15:36:05-08:00';
alert(Date.fromISO(d1)-Date.fromISO(d2)+' milliseconds')

回答by iivel

Given the differences in date formats and capability between browsers, I'd really reccomend you use a library devoted to DateTime handling. JS support for it is notoriously horrendous. I'm a HUGE fan of date.js

鉴于浏览器之间日期格式和功能的差异,我真的建议您使用专门用于 DateTime 处理的库。JS 对它的支持是出了名的可怕。我是 date.js 的超级粉丝

http://www.datejs.com/

http://www.datejs.com/