简体   繁体   English

将 UTC 日期时间转换为本地日期时间

[英]Convert UTC date time to local date time

From the server I get a datetime variable in this format: 6/29/2011 4:52:48 PM and it is in UTC time.我从服务器得到一个格式为: 6/29/2011 4:52:48 PM的日期时间变量,它是 UTC 时间。 I want to convert it to the current user's browser time zone using JavaScript.我想使用 JavaScript 将其转换为当前用户的浏览器时区。

How this can be done using JavaScript or jQuery?如何使用 JavaScript 或 jQuery 完成此操作?

Append 'UTC' to the string before converting it to a date in javascript: Append 'UTC' 到字符串,然后将其转换为 javascript 中的日期:

var date = new Date('6/29/2011 4:52:48 PM UTC');
date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"

In my point of view servers should always in the general case return a datetime in the standardized ISO 8601-format .在我看来,服务器在一般情况下应该总是以标准化的 ISO 8601 格式返回日期时间。

More info here:更多信息在这里:

IN this case the server would return '2011-06-29T16:52:48.000Z' which would feed directly into the JS Date object.在这种情况下,服务器将返回'2011-06-29T16:52:48.000Z' ,它会直接输入 JS 日期 object。

var utcDate = '2011-06-29T16:52:48.000Z';  // ISO-8601 formatted date returned from server
var localDate = new Date(utcDate);

The localDate will be in the right local time which in my case would be two hours later (DK time). localDate将在正确的本地时间,在我的情况下将是两个小时后(DK 时间)。

You really don't have to do all this parsing which just complicates stuff, as long as you are consistent with what format to expect from the server.真的不必做所有这些只会使事情复杂化的解析,只要你与服务器期望的格式一致。

This is an universal solution:这是一个通用的解决方案:

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;   
}

Usage:用法:

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

Display the date based on the client local setting:根据客户端本地设置显示日期:

date.toLocaleString();

For me above solutions didn't work.对我来说,上述解决方案不起作用。

With IE the UTC date-time conversion to local is little tricky.使用 IE,将 UTC 日期时间转换为本地时间有点棘手。 For me, the date-time from web API is '2018-02-15T05:37:26.007' and I wanted to convert as per local timezone so I used below code in JavaScript.对我来说,web API 的日期时间是'2018-02-15T05:37:26.007' ,我想根据当地时区进行转换,所以我在 JavaScript 中使用了以下代码。

var createdDateTime = new Date('2018-02-15T05:37:26.007' + 'Z');

You should get the (UTC) offset (in minutes) of the client:您应该获得客户端的 (UTC) 偏移量(以分钟为单位):

var offset = new Date().getTimezoneOffset();

And then do the correspondent adding or substraction to the time you get from the server.然后对从服务器获取的时间做相应的加减。

Hope this helps.希望这可以帮助。

This works for me:这对我有用:

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

Put this function in your head:把这个 function 记在你的脑子里:

<script type="text/javascript">
function localize(t)
{
  var d=new Date(t+" UTC");
  document.write(d.toString());
}
</script>

Then generate the following for each date in the body of your page:然后为页面正文中的每个日期生成以下内容:

<script type="text/javascript">localize("6/29/2011 4:52:48 PM");</script>

To remove the GMT and time zone, change the following line:要删除 GMT 和时区,请更改以下行:

document.write(d.toString().replace(/GMT.*/g,""));

This is a simplified solution based on Adorjan Princ´s answer:这是基于 Adorjan Princ 回答的简化解决方案:

function convertUTCDateToLocalDate(date) {
    var newDate = new Date(date);
    newDate.setMinutes(date.getMinutes() - date.getTimezoneOffset());
    return newDate;
}

or simpler (though it mutates the original date):或更简单(尽管它改变了原始日期):

function convertUTCDateToLocalDate(date) {
    date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
    return date;
}

Usage:用法:

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

After trying a few others posted here without good results, this seemed to work for me:在尝试了这里发布的其他一些没有好的结果之后,这似乎对我有用:

convertUTCDateToLocalDate: function (date) {
    return new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(),  date.getHours(), date.getMinutes(), date.getSeconds()));
}

And this works to go the opposite way, from Local Date to UTC:这适用于 go 相反的方式,从本地日期到 UTC:

convertLocalDatetoUTCDate: function(date){
    return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(),  date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
}

Add the time zone at the end, in this case 'UTC':在末尾添加时区,在本例中为“UTC”:

theDate = new Date( Date.parse('6/29/2011 4:52:48 PM UTC'));

after that, use toLocale ()* function families to display the date in the correct locale之后,使用toLocale ()* function 系列以正确的语言环境显示日期

theDate.toLocaleString();  // "6/29/2011, 9:52:48 AM"
theDate.toLocaleTimeString();  // "9:52:48 AM"
theDate.toLocaleDateString();  // "6/29/2011"

if you have 2021-12-28T18:00:45.959Z format you can use this in js:如果你有2021-12-28T18:00:45.959Z格式,你可以在 js 中使用它:

// myDateTime is 2021-12-28T18:00:45.959Z

myDate = new Date(myDateTime).toLocaleDateString('en-US');
// myDate is 12/28/2021

myTime = new Date(myDateTime).toLocaleTimeString('en-US');
// myTime is 9:30:45 PM

you just have to put your area string instead of "en-US" (eg "fa-IR").您只需要输入您的区域字符串而不是“en-US”(例如“fa-IR”)。


also you can use options for toLocaleTimeString like { hour: '2-digit', minute: '2-digit' }您也可以使用toLocaleTimeString的选项,例如 { hour: '2-digit', minute: '2-digit' }

myTime = new Date(myDateTime).toLocaleTimeString('en-US',{ hour: '2-digit', minute: '2-digit' });
// myTime is 09:30 PM

more information for toLocaleTimeString and toLocaleDateString有关toLocaleTimeStringtoLocaleDateString的更多信息

Use this for UTC and Local time convert and vice versa .将此用于UTC 和本地时间转换,反之亦然

//Covert datetime by GMT offset 
//If toUTC is true then return UTC time other wise return local time
function convertLocalDateToUTCDate(date, toUTC) {
    date = new Date(date);
    //Local time converted to UTC
    console.log("Time: " + date);
    var localOffset = date.getTimezoneOffset() * 60000;
    var localTime = date.getTime();
    if (toUTC) {
        date = localTime + localOffset;
    } else {
        date = localTime - localOffset;
    }
    date = new Date(date);
    console.log("Converted time: " + date);
    return date;
}

Matt's answer is missing the fact that the daylight savings time could be different between Date() and the date time it needs to convert - here is my solution: Matt 的回答忽略了这样一个事实,即 Date() 和它需要转换的日期时间之间的夏令时可能不同——这是我的解决方案:

    function ConvertUTCTimeToLocalTime(UTCDateString)
    {
        var convertdLocalTime = new Date(UTCDateString);

        var hourOffset = convertdLocalTime.getTimezoneOffset() / 60;

        convertdLocalTime.setHours( convertdLocalTime.getHours() + hourOffset ); 

        return convertdLocalTime;
    }

And the results in the debugger:以及调试器中的结果:

UTCDateString: "2014-02-26T00:00:00"
convertdLocalTime: Wed Feb 26 2014 00:00:00 GMT-0800 (Pacific Standard Time)

In case you don't mind using moment.js and your time is in UTC just use the following:如果你不介意使用moment.js并且你的时间是 UTC 只需使用以下内容:

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

if your time is not in utc but any other locale known to you, then use following:如果您的时间不是 utc,而是您知道的任何其他语言环境,请使用以下内容:

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

if your time is already in local, then use following:如果您的时间已经在本地,请使用以下内容:

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

To me the simplest seemed using对我来说最简单的似乎是使用

datetime.setUTCHours(datetime.getHours());
datetime.setUTCMinutes(datetime.getMinutes());

(i thought the first line could be enough but there are timezones which are off in fractions of hours) (我认为第一行就足够了,但有些时区会在几小时内关闭)

Using YYYY-MM-DD hh:mm:ss format:使用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)"

For converting from the YYYY-MM-DD hh:mm:ss format, make sure your date follow the ISO 8601 format .要从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)

Important things to note需要注意的重要事项

  1. You must separate the date and the time by a T , a space will not work in some browsers您必须用T分隔日期和时间,空格在某些浏览器中不起作用
  2. You must set the timezone using this format +hh:mm , using a string for a timezone (ex. : 'UTC') will not work in many browsers.您必须使用此格式设置时区+hh:mm ,使用字符串作为时区(例如:'UTC')在许多浏览器中不起作用。 +hh:mm represent the offset from the UTC timezone. +hh:mm表示与 UTC 时区的偏移量。

A JSON date string (serialized in C#) looks like "2015-10-13T18:58:17". JSON 日期字符串(在 C# 中序列化)看起来像“2015-10-13T18:58:17”。

In angular, (following Hulvej) make a localdate filter:在 angular 中,(跟随 Hulvej)制作一个localdate过滤器:

myFilters.filter('localdate', function () {
    return function(input) {
        var date = new Date(input + '.000Z');
        return date;
    };
})

Then, display local time like:然后,显示本地时间,如:

{{order.createDate | localdate | date : 'MMM d, y h:mm a' }}

For me, this works well对我来说,这很好用

if (typeof date === "number") {
  time = new Date(date).toLocaleString();
  } else if (typeof date === "string"){
  time = new Date(`${date} UTC`).toLocaleString();
}

This is what I'm doing to convert UTC to my Local Time:这就是我将 UTC 转换为我的本地时间所做的事情:

 const dataDate = '2020-09-15 07:08:08' const utcDate = new Date(dataDate); const myLocalDate = new Date(Date.UTC( utcDate.getFullYear(), utcDate.getMonth(), utcDate.getDate(), utcDate.getHours(), utcDate.getMinutes() )); document.getElementById("dataDate").innerHTML = dataDate; document.getElementById("myLocalDate").innerHTML = myLocalDate;
 <p>UTC<p> <p id="dataDate"></p> <p>Local(GMT +7)<p> <p id="myLocalDate"></p>

Result: Tue Sep 15 2020 14:08:00 GMT+0700 (Indochina Time).结果:2020 年 9 月 15 日星期二 14:08:00 GMT+0700(印度支那时间)。

I Answering This If Any one want function that display converted time to specific id element and apply date format string yyyy-mm-dd here date1 is string and ids is id of element that time going to display.我回答这个如果有人想要 function 将转换后的时间显示到特定的 id 元素并应用日期格式字符串 yyyy-mm-dd,这里 date1 是字符串,ids 是该时间要显示的元素的 id。

function convertUTCDateToLocalDate(date1, ids) 
{
  var newDate = new Date();
  var ary = date1.split(" ");
  var ary2 = ary[0].split("-");
  var ary1 = ary[1].split(":");
  var month_short = Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
  newDate.setUTCHours(parseInt(ary1[0]));
  newDate.setUTCMinutes(ary1[1]);
  newDate.setUTCSeconds(ary1[2]);
  newDate.setUTCFullYear(ary2[0]);
  newDate.setUTCMonth(ary2[1]);
  newDate.setUTCDate(ary2[2]);
  ids = document.getElementById(ids);
  ids.innerHTML = " " + newDate.getDate() + "-" + month_short[newDate.getMonth() - 1] + "-" + newDate.getFullYear() + " " + newDate.getHours() + ":" + newDate.getMinutes() + ":" + newDate.getSeconds();
            }

i know that answer has been already accepted but i get here cause of google and i did solve with getting inspiration from accepted answer so i did want to just share it if someone need.我知道答案已经被接受,但我来到这里是因为谷歌,我确实通过从接受的答案中获得灵感来解决问题,所以我确实想在有人需要的时候分享它。

@Adorojan's answer is almost correct. @Adorojan's回答几乎是正确的。 But addition of offset is not correct since offset value will be negative if browser date is ahead of GMT and vice versa.但是添加偏移量是不正确的,因为如果浏览器日期早于 GMT,偏移量值将为负,反之亦然。 Below is the solution which I came with and is working perfectly fine for me:以下是我提供的解决方案,对我来说工作得很好:

 // 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); }

Based on @digitalbath answer, here is a small function to grab the UTC timestamp and display the local time in a given DOM element (using jQuery for this last part):基于@digitalbath 的回答,这里有一个小的 function 来获取 UTC 时间戳并在给定的 DOM 元素中显示本地时间(最后一部分使用 jQuery):

https://jsfiddle.net/moriz/6ktb4sv8/1/ https://jsfiddle.net/moriz/6ktb4sv8/1/

<div id="eventTimestamp" class="timeStamp">
   </div>
   <script type="text/javascript">
   // Convert UTC timestamp to local time and display in specified DOM element
   function convertAndDisplayUTCtime(date,hour,minutes,elementID) {
    var eventDate = new Date(''+date+' '+hour+':'+minutes+':00 UTC');
    eventDate.toString();
    $('#'+elementID).html(eventDate);
   }
   convertAndDisplayUTCtime('06/03/2015',16,32,'eventTimestamp');
   </script>

You can use momentjs , moment(date).format() will always give result in local date .您可以使用momentjsmoment(date).format()将始终以本地日期给出结果。

Bonus , you can format in any way you want.奖金,你可以用任何你想要的方式格式化。 For eg.例如。

moment().format('MMMM Do YYYY, h:mm:ss a'); // September 14th 2018, 12:51:03 pm
moment().format('dddd');                    // Friday
moment().format("MMM Do YY"); 

For more details you can refer Moment js website有关更多详细信息,您可以参考Moment js 网站

this worked well for me with safari/chrome/firefox:这对我来说很适合 safari/chrome/firefox:

const localDate = new Date(`${utcDate.replace(/-/g, '/')} UTC`);

I believe this is the best solution:我相信这是最好的解决方案:

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

This will update your date by the offset appropriately since it is presented in minutes.这将通过偏移量适当地更新您的日期,因为它以分钟为单位显示。

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

The source string must specify a time zone or UTC.源字符串必须指定时区或 UTC。

One-liner:单线:

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

Result in one of my web browsers:结果出现在我的 web 浏览器之一中:

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

This approach even selects standard/daylight time appropriately.这种方法甚至可以适当地选择标准/夏令时。

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

Result in my browser:结果在我的浏览器中:

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

using dayjs library:使用 dayjs 库:

(new Date()).toISOString();  // returns 2021-03-26T09:58:57.156Z  (GMT time)

dayjs().format('YYYY-MM-DD HH:mm:ss,SSS');  // returns 2021-03-26 10:58:57,156  (local time)

(in nodejs, you must do before using it: const dayjs = require('dayjs'); in other environtments, read dayjs documentation.) (在 nodejs 中,你必须在使用它之前做: const dayjs = require('dayjs');在其他环境中,阅读 dayjs 文档。)

This works on my side这对我有用

Option 1: If date format is something like "yyyy-mm-dd" or "yyyy-mm-dd H:n:s", ex: "2021-12-16 06:07:40"选项 1:如果日期格式类似于“yyyy-mm-dd”或“yyyy-mm-dd H:n:s”,例如:“2021-12-16 06:07:40”

With this format It doesnt really know if its a local format or a UTC time.使用这种格式,它真的不知道它是本地格式还是 UTC 时间。 So since we know that the date is a UTC we have to make sure that JS will know that its a UTC.因此,由于我们知道日期是 UTC,因此我们必须确保 JS 知道它是 UTC。 So we have to set the date as UTC.所以我们必须将日期设置为 UTC。

        function setDateAsUTC(d) {
            let date = new Date(d);
            return new Date(
                Date.UTC(
                    date.getFullYear(),
                    date.getMonth(),
                    date.getDate(),
                    date.getHours(),
                    date.getMinutes(),
                    date.getSeconds()
                )
            );
        }

and then use it然后使用它


let d = "2021-12-16 06:07:40";
setDateAsUTC(d).toLocaleString();

// output: 12/16/2021, 6:07:40 AM

Options 2: If UTC date format is ISO-8601.选项 2:如果 UTC 日期格式是 ISO-8601。 Mostly servers timestampz format are in ISO-8601 ex: '2011-06-29T16:52:48.000Z'.大多数服务器 timestampz 格式采用 ISO-8601,例如:'2011-06-29T16:52:48.000Z'。 With this we can just pass it to the date function and toLocaleString() function.这样我们就可以将它传递给日期 function 和 toLocaleString() function。

let newDate = "2011-06-29T16:52:48.000Z"
new Date(newDate).toLocaleString();
//output: 6/29/2011, 4:52:48 PM

In Angular I used Ben's answer this way:在 Angular 中,我这样使用了 Ben 的回答:

$scope.convert = function (thedate) {
    var tempstr = thedate.toString();
    var newstr = tempstr.toString().replace(/GMT.*/g, "");
    newstr = newstr + " UTC";
    return new Date(newstr);
};

Edit: Angular 1.3.0 added UTC support to date filter, I haven't use it yet but it should be easier, here is the format:编辑:Angular 1.3.0 为日期过滤器添加了 UTC 支持,我还没有使用它但应该更容易,这是格式:

{{ date_expression | date : format : timezone}}

Angular 1.4.3 Date API Angular 1.4.3 日期 API

I wrote a nice little script that takes a UTC epoch and converts it the client system timezone and returns it in d/m/YH:i:s (like the PHP date function) format:我写了一个不错的小脚本,它采用 UTC 纪元并将其转换为客户端系统时区,并以 d/m/YH:i:s(如 PHP 日期函数)格式返回:

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;

};

I've created one function which converts all the timezones into local time.我创建了一个 function 将所有时区转换为本地时间。

I did not used getTimezoneOffset(), because it does not returns proper offset value我没有使用 getTimezoneOffset(),因为它不会返回正确的偏移值

Requirements:要求:

1. npm i moment-timezone

function utcToLocal(utcdateTime, tz) {
    var zone = moment.tz(tz).format("Z") // Actual zone value e:g +5:30
    var zoneValue = zone.replace(/[^0-9: ]/g, "") // Zone value without + - chars
    var operator = zone && zone.split("") && zone.split("")[0] === "-" ? "-" : "+" // operator for addition subtraction
    var localDateTime
    var hours = zoneValue.split(":")[0]
    var minutes = zoneValue.split(":")[1]
    if (operator === "-") {
        localDateTime = moment(utcdateTime).subtract(hours, "hours").subtract(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
    } else if (operator) {
        localDateTime = moment(utcdateTime).add(hours, "hours").add(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
    } else {
        localDateTime = "Invalid Timezone Operator"
    }
    return localDateTime
}

utcToLocal("2019-11-14 07:15:37", "Asia/Kolkata")

//Returns "2019-11-14 12:45:37"

In my case, I had to find the difference of dates in seconds.就我而言,我必须找出以秒为单位的日期差异。 The date was a UTC date string, so I converted it to a local date object. This is what I did:日期是 UTC 日期字符串,因此我将其转换为本地日期 object。这就是我所做的:

let utc1 = new Date();
let utc2 = null;
const dateForCompare = new Date(valueFromServer);
dateForCompare.setTime(dateForCompare.getTime() - dateForCompare.getTimezoneOffset() * 
 60000);
utc2 = dateForCompare;

const seconds = Math.floor(utc1 - utc2) / 1000;

UTC to local to ISO - Using Molp Burnbright answer UTC 到本地到 ISO - 使用 Molp Burnbright 答案

because server only accepts ISO date-time so I converted UTC to my local timezone and sent it to server in ISO format因为服务器只接受 ISO 日期时间所以我将 UTC 转换为本地时区并以 ISO 格式将其发送到服务器

declare this somewhere在某处声明

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

and do this where you need local datetime in ISO format convertUTCDateToLocalDate(date).toISOString()并在需要 ISO 格式的本地日期时间的地方执行此操作convertUTCDateToLocalDate(date).toISOString()

I had a similar problem, I used following code code (JavaScript) to convert UTC to local time我遇到了类似的问题,我使用以下代码(JavaScript)将 UTC 转换为本地时间

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

In JavaScript I used:在 JavaScript 中,我使用了:

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

{{updaated_time | date: 'dd-MM-yyyy HH:mm'}} //output: 26-10-2022 12:00
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;
}

For others who visit - use this function to get a Local date object from a UTC string, should take care of DST and will work on IE, IPhone etc.对于访问的其他人 - 使用此 function 从 UTC 字符串中获取本地日期 object,应该注意 DST 并将在 IE、iPhone 等上工作。

We split the string (Since JS Date parsing is not supported on some browsers) We get difference from UTC and subtract it from the UTC time, which gives us local time.我们拆分字符串(因为某些浏览器不支持 JS 日期解析)我们从 UTC 中获取差异并从 UTC 时间中减去它,这给了我们本地时间。 Since offset returned is calculated with DST (correct me if I am wrong), so it will set that time back in the variable "utc".由于返回的偏移量是用 DST 计算的(如果我错了请纠正我),所以它会将那个时间设置回变量“utc”。 Finally return the date object.最后返回日期object。

You can get it done using moment.js file.您可以使用moment.js文件完成它。

Its simple you have just mention the place of the timezone.很简单,您刚刚提到了时区的位置。

Example: If you to convert your datetime to Asia/Kolkata timezone,you have to just mention the name of the timezone place obtained from moment.js示例:如果您要将日期时间转换为 Asia/Kolkata 时区,则只需提及从moment.js获得的时区名称

 var UTCDateTime="Your date obtained from UTC"; var ISTleadTime=(moment.tz(UTCDateTime, "Africa/Abidjan")).tz("Asia/Kolkata").format('YYYY-MM-DD LT');

For the TypeScript users, here is a helper function:对于 TypeScript 用户,这里有一个助手 function:

// 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;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM