在javascript/jquery中解析UTC ISO日期到本地时间日期

parsing a UTC ISO date to a local time date in javascript/jquery

本文关键字:日期 ISO 时间 UTC javascript jquery      更新时间:2023-09-26

我已经试着去寻找答案了,虽然我发现的答案非常相似,但我不认为它们正是我想要的。如果这个问题已经在其他地方得到了解答,请原谅我。

我试图在javascript中解析ISO日期,以便我可以将其与客户端系统日期进行比较,并根据ISO日期在客户端系统日期之前或之后显示信息。

这很好,直到我需要支持IE8,现在我卡住了。

我创建了一个函数,因为我需要对三个不同的日期执行此操作。

例如,我的ISO日期是:2015-12-22T11:59在UTC时间。

但是一旦我的日期被解析,完整的日期是11:59在当地时间,无论我测试哪个时区,它总是11.59在那个时区。

我知道我所创建的函数目前不做任何与时区,这就是我卡住的地方。我不知道要添加什么来将结束日期更改为客户端机器时区的反映。

任何帮助或建议都将不胜感激。我不能使用像moments.js这样的东西,因为我有上传限制。

Jquery是可用的。或者纯javascript。

<script>
function setSaleContent() {

    //creating a new date object that takes the clients current system time. so we can compare it to the dates stored in our array
    var currentDate = new Date();
    console.log(currentDate + " this is the clients date ");

    //These variables actually come from an external array object, but I'm putting them in here like this for this example. 
    var destinations = {
        freedate: "2015-12-16T11:59",  
        courierdate: "2015-12-22T11:59",
        nextdaydate: "2015-12-23T11:59",
    }
    //fetch all the ISO dates from the array. 
    var freeDateISO = destinations["freedate"];
    var courierDateISO = destinations["courierdate"];
    var nextdayDateISO = destinations["nextdaydate"];

    //I am creating this reusable function to split up my ISO date for the sake of IE8.. and create it into a date format that can be compared against another date.  I know that this isn't doing anything with my timezone and that is where my problem lies. 
    function parseDate(str) {
        var parts = /^('d{4}).('d{2}).('d{2}).('d{2}):('d{2})/.exec(str);
        if (parts) {
            return new Date(parts[1], parts[2] - 1, parts[3], parts[4], parts[5]);
        }
        return new Date();
    }

    //I would like this date to change to reflect the time zone of the clients system time. 
    //currently returns the date at 11.59 regardless of timezone. 
    //If i was in GMT  i would want it to say 11.59
    //If i was in CT time I would like this to say 05.59
    //If i was in Perth I would like this to say  19:59
    var freeDate = parseDate(freeDateISO);
    console.log(freeDate + " this is the converted date for IE")


}

window.onload = setSaleContent;

简单的解决方案是将Z附加到ISO日期后,以表明它是UTC时间,例如2015-12-22T11:59Z

当JavaScript将该日期解析为字符串时,它将自动将UTC日期转换为本地时区。

虽然这对于new Date(str);形式的解析调用来说足够简单,但对于针对IE8和其他旧浏览器的带有数值参数的解析调用来说,它不会发挥良好的作用。

Javascript JSON日期解析在IE7/IE8返回NaN
这可以替换您的自定义parseDate函数,经过一些修改,以接受输入字符串。

或者,在新创建的日期上使用.getTimezoneOffset()方法实现您自己的自定义日期操作程序来考虑本地时区,该方法以分钟为单位给出时区偏移量,但由于JavaScript日期对象的方法有限,您将不得不提出利用偏移量的方法,例如调整小时和分钟。