从服务器我得到一个datetime变量的格式:6/29/2011 4:52:48 PM,它是UTC时间。我想使用JavaScript将其转换为当前用户的浏览器时区。

如何使用JavaScript或jQuery来做到这一点?


当前回答

我相信这是最好的解决方案:

  let date = new Date(objDate);
  date.setMinutes(date.getTimezoneOffset());

这将根据偏移量适当地更新您的日期,因为它是以分钟为单位的。

其他回答

function getUTC(str) {
    var arr = str.split(/[- :]/);
    var utc = new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5]);
    utc.setTime(utc.getTime() - utc.getTimezoneOffset()*60*1000)
    return utc;
}

对于其他访问的人-使用此函数从UTC字符串中获取本地日期对象,应该关心DST,并将在IE, IPhone等上工作。

我们分割字符串(因为JS日期解析在某些浏览器上不支持) 我们得到UTC的差值,然后用UTC时间减去它,得到当地时间。由于返回的偏移量是用DST计算的(如果我错了请纠正我),所以它将在变量“utc”中设置该时间。最后返回date对象。

这是一个普遍的解决方案:

function convertUTCDateToLocalDate(date) {
    var newDate = new Date(date.getTime()+date.getTimezoneOffset()*60*1000);

    var offset = date.getTimezoneOffset() / 60;
    var hours = date.getHours();

    newDate.setHours(hours - offset);

    return newDate;   
}

用法:

var date = convertUTCDateToLocalDate(new Date(date_string_you_received));

根据客户端本地设置显示日期:

date.toLocaleString();

我有一个类似的问题,我使用以下代码代码(JavaScript)转换UTC到本地时间

let a = new Date() .toString a = a.getFullYear () () + "-" + ( a.getMonth () + 1) .toString()。padStart(2, "0") + "-" + a.getDate(). tostring()。padStart(“0”) console.log (a)

采用YYYY-MM-DD hh:mm:ss格式:

var date = new Date('2011-06-29T16:52:48+00:00');
date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"

要从YYYY-MM-DD hh:mm:ss格式转换,请确保您的日期遵循ISO 8601格式。

Year: 
    YYYY (eg 1997)    
Year and month: 
    YYYY-MM (eg 1997-07)
Complete date: 
    YYYY-MM-DD (eg 1997-07-16)
Complete date plus hours and minutes:
    YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)    
Complete date plus   hours, minutes and seconds:
    YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)    
Complete date plus hours, minutes, seconds and a decimal fraction of a second
    YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00) where:

YYYY = four-digit year
MM   = two-digit month (01=January, etc.)
DD   = two-digit day of month (01 through 31)
hh   = two digits of hour (00 through 23) (am/pm NOT allowed)
mm   = two digits of minute (00 through 59)
ss   = two digits of second (00 through 59)
s    = one or more digits representing a decimal fraction of a second
TZD  = time zone designator (Z or +hh:mm or -hh:mm)

需要注意的重要事项

你必须用T分隔日期和时间,空格在某些浏览器中不起作用 您必须使用这种格式+hh:mm设置时区,使用字符串作为时区(例如:'UTC')将在许多浏览器中不起作用。+hh:mm表示与UTC时区的偏移量。

如果你不介意使用moment.js,并且你的时间是UTC时间,请使用以下格式:

moment.utc('6/29/2011 4:52:48 PM').toDate();

如果您的时间不是utc,而是您所知道的任何其他地区,则使用以下方法:

moment('6/29/2011 4:52:48 PM', 'MM-DD-YYYY', 'fr').toDate();

如果你的时间已经在本地,那么使用以下方法:

moment('6/29/2011 4:52:48 PM', 'MM-DD-YYYY');