【问题标题】:Invalid date issue using new Date()使用 new Date() 的无效日期问题
【发布时间】:2017-11-23 11:04:57
【问题描述】:

我正在将时间戳传递给下面的函数,它正确地返回了日期字符串,但是当我在下面执行时,它给了我错误的无效日期。

        var postDate = new Date(this.ConvertServerDateToLocal(timestamp));

 //postDate returns invalid date object.


        ConvertServerDateToLocal: function(dateInput){
            // EST - UTC offset: 4 hours

            var offset = 4.0,
            /*
             - calculate the difference between the server EST date and UTC
             - the value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00 UTC.
             - the time-zone offset is the difference, in minutes, between UTC and local time
             - 60000 milliseconds = 60 seconds = 1 minute
             */
                serverDate = new Date(dateInput),
                utc = serverDate.getTime() - (serverDate.getTimezoneOffset() * 60000),
             /*
             - apply the offset between UTC and EST (4 hours)
             - 3600000 milliseconds = 3600 seconds = 60 minutes = 1 hour
             */
             clientDate = new Date(utc + (3600000 * offset));
            return clientDate.toLocaleString();
        }

下面是我传递给 ConvertServerDateToLocal() 函数的示例时间戳。

timestamp = "Nov 22, 2017 23:05:58" // 在输出后抛出无效日期

timestamp = "Nov 09, 2017 18:30:19" // 正常工作

【问题讨论】:

    标签: javascript jquery extjs sencha-touch


    【解决方案1】:
    function ConvertServerDateToLocal(dateInput) {
        // EST - UTC offset: 4 hours
        dateInput = "Nov 09, 2017 18:30:19";
        var offset = 4.0,
        /*
         - calculate the difference between the server EST date and UTC
         - the value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00 UTC.
         - the time-zone offset is the difference, in minutes, between UTC and local time
         - 60000 milliseconds = 60 seconds = 1 minute
         */
        serverDate = new Date(dateInput.toString());
    
        utc = serverDate.getTime() - (serverDate.getTimezoneOffset() * 60000);
    
        /*
        - apply the offset between UTC and EST (4 hours)
        - 3600000 milliseconds = 3600 seconds = 60 minutes = 1 hour
         */
        clientDate = new Date(utc + (3600000 * offset));
    
        //return clientDate.toLocaleString();
        alert(clientDate.toLocaleString());
    }
    

    将输入参数转换为字符串对我有用。但我不确定为什么一个日期有效而另一个无效。如果您找到了答案,请在此处发布。我也经常使用 Dates,它们总是很痛苦。

    【讨论】:

      猜你喜欢
      • 2016-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-24
      • 1970-01-01
      • 2021-06-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多