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

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


当前回答

@Adorojan的回答几乎是正确的。但是添加偏移量是不正确的,因为如果浏览器日期在GMT之前,偏移量值将为负,反之亦然。 下面是我的解决方案,对我来说是完美的:

// Input time in UTC var inputInUtc = "6/29/2011 4:52:48"; var dateInUtc = new Date(Date.parse(inputInUtc+" UTC")); //Print date in UTC time document.write("Date in UTC : " + dateInUtc.toISOString()+"<br>"); var dateInLocalTz = convertUtcToLocalTz(dateInUtc); //Print date in local time document.write("Date in Local : " + dateInLocalTz.toISOString()); function convertUtcToLocalTz(dateInUtc) { //Convert to local timezone return new Date(dateInUtc.getTime() - dateInUtc.getTimezoneOffset()*60*1000); }

其他回答

我有一个类似的问题,我使用以下代码代码(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)

我写了一个漂亮的小脚本,它采用UTC纪元并将其转换为客户端系统时区,并以d/m/Y H: I:s(类似于PHP date函数)格式返回:

getTimezoneDate = function ( e ) {

    function p(s) { return (s < 10) ? '0' + s : s; }        

    var t = new Date(0);
    t.setUTCSeconds(e);

    var d = p(t.getDate()), 
        m = p(t.getMonth()+1), 
        Y = p(t.getFullYear()),
        H = p(t.getHours()), 
        i = p(t.getMinutes()), 
        s = p(t.getSeconds());

    d =  [d, m, Y].join('/') + ' ' + [H, i, s].join(':');

    return d;

};

对于TypeScript用户,这里有一个helper函数:

// Typescript Type: Date Options
interface DateOptions {
  day: 'numeric' | 'short' | 'long',
  month: 'numeric',
  year: 'numeric',
  timeZone: 'UTC',
};

// Helper Function: Convert UTC Date To Local Date
export const convertUTCDateToLocalDate = (date: Date) => {
  // Date Options
  const dateOptions: DateOptions = {
    day: 'numeric',
    month: 'numeric',
    year: 'numeric',
    timeZone: 'UTC',
  };

  // Formatted Date (4/20/2020)
  const formattedDate = new Date(date.getTime() - date.getTimezoneOffset() * 60 * 1000).toLocaleString('en-US', dateOptions);
  return formattedDate;
};

tl;dr (new Date('6/29/2011 4:52:48 PM UTC')).toString()

源字符串必须指定时区或UTC。

一行程序:

(new Date('6/29/2011 4:52:48 PM UTC')).toString()

结果在我的一个web浏览器:

"Wed Jun 29 2011 09:52:48 GMT-0700 (Pacific Daylight Time)"

这种方法甚至适当地选择标准/日光时间。

(new Date('1/29/2011 4:52:48 PM UTC')).toString()

结果在我的浏览器:

"Sat Jan 29 2011 08:52:48 GMT-0800 (Pacific Standard Time)"

在JavaScript中,我使用:

var updaated_time= "2022-10-25T06:47:42.000Z"

{{updaated_time | date: 'dd-MM-yyyy HH:mm'}} //output: 26-10-2022 12:00