Javascript日期时间字符串到UTC日期时间和UTC到本地日期时间 [英] Javascript Date time String to UTC date time and UTC to Local Date time

查看:110
本文介绍了Javascript日期时间字符串到UTC日期时间和UTC到本地日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将字符串转换为UTC日期,然后将UTC日期转换为本地日期。

i needed to convert string to UTC date , and then UTC date to local date.

这是我的代码:

var dateStr = "9/8/2015 12:44:00 PM";
console.log(strtoUTCtoLocal(dateStr));

function strtoUTCtoLocal(dateStr)
{
    var d1 = new Date(dateStr).toUTCString();
    var d2= new Date(d1);

     return      "0" + (d2.getMonth()+1).toString().slice(-2) + "/" +
                 "0" + d2.getDate().toString().slice(-2) + "/" +
                 d2.getFullYear().toString() + " " +
                 d2.getHours().toString() + ":" + 
                 d2.getMinutes().toString();
}


推荐答案

分析日期字符串应该完成因为 Date.parse 在浏览器之间是不一致的。假设您的格式是d / m / y,您可以使用以下内容将其解析为UTC时间:

Parsing date strings should be done manually since Date.parse is inconsistent across browsers. Assuming your format is d/m/y, you can parse it to a UTC time using the following:

    var s = '9/8/2015 12:44:00 PM';

    function parseDate(s) {
      var b = s.split(/\D+/);
      var ap = /pm$/i.test(s)? 12 : 0;
      return new Date(Date.UTC(b[2], b[1]-1, b[0], ((b[3]%12) + ap), b[4], b[5]));
    }

    document.write(parseDate(s));

需要验证日期,您需要一个额外的代码行。

If you need to validate the date, you'll need an extra line of code.

请注意,默认情况下,没有时区的字符串通常被解析为本地(ISO 8601除外)使用Date.parse在ES5中格式化字符串,但ECMAScript 2015会将其解析为本地,并将其更改为UTC with ECMAScript 2016)。

Note that by default, strings without a timezone are generally parsed as local (except for ISO 8601 format strings in ES5 using Date.parse, but ECMAScript 2015 parses them as local, which was changed to UTC with ECMAScript 2016).

这篇关于Javascript日期时间字符串到UTC日期时间和UTC到本地日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆