简体   繁体   English

如何使用javascript比较两个日期时间与时区偏移(比较大于或小于)

[英]How to compare two datetimes with time zone offset using javascript (comparison greater than or less than)

So I have a scenario where I need to compare Date1 and Date2所以我有一个场景,我需要比较 Date1 和 Date2
where Date1 = 05.01.2008 6:00 +5:00其中Date1 = 05.01.2008 6:00 +5:00
and Date2 = 05.01.2008 7:00 +5:00Date2 = 05.01.2008 7:00 +5:00
I am not getting a way to convert these datetimeoffsets to a particular conversion format.我没有办法将这些datetimeoffsets转换为特定的转换格式。 Plz help.请帮忙。
Here is what all i have tried till now这是我迄今为止所尝试的

function validate()
    {
        var a = document.getElementById("txtDate1").innerHTML;
        var b = document.getElementById("txtDate2").innerHTML;
        if (a > b) {
            alert('greater')
        }
        else {
            alert('Smaller')
        }
    }

use below code.使用下面的代码。 using Date.parse使用Date.parse

 var date1 = new Date(Date.parse("05.01.2008 6:00 +5:00")); var date2 = new Date(Date.parse("05.01.2008 7:00 +5:00")); if (date1 < date2) { alert('Smaller') } else if (date1 > date2) { alert('greater') } else { alert("date1 === date2"); }

You would first need to parse them as Date objects for comparison.您首先需要将它们解析为 Date 对象进行比较。 One popular option is using moment.js , since it can interpret many formats.一种流行的选择是使用moment.js ,因为它可以解释多种格式。 Then you can compare them by using Date.prototype.getTime function to get the Unix timestamp, which all use the same time zone.然后你可以通过使用Date.prototype.getTime函数来比较它们得到Unix时间戳,它们都使用相同的时区。

The way you compare them at the moment is as String types, which will not work.您目前比较它们的方式是 String 类型,这是行不通的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM