524

From the server I get a datetime variable in this format: 6/29/2011 4:52:48 PM and it is in UTC time. I want to convert it to the current user’s browser time zone using JavaScript.

How this can be done using JavaScript or jQuery?

John Pick
  • 5,562
  • 31
  • 31
Amr Elgarhy
  • 66,568
  • 69
  • 184
  • 301
  • Code Sample here: [http://stackoverflow.com/questions/3830418/is-there-a-jquery-plugin-to-convert-utc-datetimes-to-local-user-timezone](http://stackoverflow.com/questions/3830418/is-there-a-jquery-plugin-to-convert-utc-datetimes-to-local-user-timezone) – Andrew Lewis Jun 29 '11 at 18:42
  • 7
    Be careful. That's a weird date format, so be sure to specify it in whatever solution you use. If possible, get the server to send the date in ISO format. – Michael Scheper Jan 10 '17 at 04:00
  • Hello, I had similar problems, I solved it by converting the date/time, before sending to the server, using: var date = new Date('2020-11-06T01:30:00.000Z'); console.log(date.toLocaleDateString()); console.log(date.toLocaleString()); console.log(date.toLocaleTimeString()); – FXLima Sep 21 '22 at 17:49
  • My comment is to Example: (UTC Brazil) I typed "**15**/12/2020 **22:30**:00" and it sent: '2020-12-**16**T**01:30**:00.000Z'. – FXLima Sep 21 '22 at 18:01

39 Answers39

554

Append 'UTC' to the string before converting it to a date in 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)"
digitalbath
  • 7,008
  • 2
  • 17
  • 15
  • 6
    function localizeDateStr (date_to_convert_str) { var date_to_convert = new Date(date_to_convert_str); var local_date = new Date(); date_to_convert.setHours(date_to_convert.getHours()+local_date.getTimezoneOffset()); return date_to_convert.toString(); } – matt Oct 09 '12 at 17:08
  • 5
    @matt offSet returns minutes, not hours, you need to divide by 60 – bladefist May 18 '13 at 16:13
  • @matt also note there are timezones which are fractions of hours off. and you don't need to use timezone offset when there are getter and setter functions for both UTC and local values – mizuki nakeshu Jun 14 '13 at 09:44
  • does this take into account the offset ? – euther Mar 10 '14 at 03:23
  • 88
    This assumes that the date part of the string is following the US standard, mm/dd/YYYY, which is not obviously the case in Europe and in other parts of the world. – AsGoodAsItGets Jan 14 '15 at 16:49
  • 1
    Also worth noting `.toLocaleString()` uses locale-specific formatting, too. However, as far as I can tell the input must be in the format shown here. – Alex S Jul 31 '17 at 02:17
  • 10
    @digitalbath Works on Chrome but doesn't work on Firefox. – Ganesh Satpute Sep 05 '17 at 13:30
  • @GaneshSatpute just tried on Firefox 52.3.0, and it works just fine. – digitalbath Sep 20 '17 at 19:31
  • 12
    `!` __Beware__ `!` _[…parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies…](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) (which probably was even more true in 2011) – Stphane Feb 16 '18 at 08:08
  • How are we doing for this now that it's some years on in 2018? Are there still compatibility issues with Firefox/IE? – egmfrs Sep 14 '18 at 16:02
  • @egmfrs—completely agree, this is a really bad answer. – RobG Sep 21 '18 at 10:58
  • 1
    Yes, this answer is very misleading. `getTimezoneOffset()` HAS to be involved if you want to get correct results for DST in different countries etc. – David Schumann Nov 02 '18 at 09:07
  • 1. getTimezoneOffset() today (21 June) returns -60 in UK. That is "minutes" offset from UTC. So, it cannot be simply added to current hours. 2. What happens when it is around midnight and it change the day ? I don't think setHours() takes care of this. – Alex 75 Jun 21 '19 at 09:35
  • Still not work with firefox, I am using firefox developer version 79.0b9. – Duke Jul 22 '20 at 09:06
  • 2
    This answer should not be the accepted answer. It lacks support of common browsers, and introduces bad practices. – Hultan Apr 11 '22 at 10:16
  • 2023 - still not work for firefox unfortunately. – chotkos Feb 06 '23 at 10:43
  • what if we have already the date in a var? – serge Jul 06 '23 at 15:22
277

In my point of view servers should always in the general case return a datetime in the standardized ISO 8601-format.

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.

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).

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.

Dan Dascalescu
  • 143,271
  • 52
  • 317
  • 404
Hulvej
  • 3,895
  • 1
  • 18
  • 21
  • 1
    how to get iso format date? i am getting date in UTC format with UTC appended to the end – Deepika Jul 28 '15 at 09:46
  • 14
    @Colin that's language dependent. In C# you can format a `DateTime` object with `.toString("o")` which returns a ISO-8601 formatted string as shown above. https://msdn.microsoft.com/en-us/library/zdtaw1bw(v=vs.110).aspx In javascript it's `new Date().toISOString()`. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString – Hulvej Aug 04 '15 at 18:29
  • 7
    For some reason, appending UTC to my timestamp did not work. But appending a 'z' did. – Chaster johnson Jun 03 '21 at 04:48
  • @Chaster johnson, nice catch. I was using Python's datetime.isoformat() to send some datetime info to my js frontend and adding 'Z' everything sorted out. Checking isoformat source, they do not have an option to add 'Z'. I manually added 'Z' to the end of isoformat output. https://stackoverflow.com/questions/19654578/python-utc-datetime-objects-iso-format-doesnt-include-z-zulu-or-zero-offset – JM217 Sep 18 '21 at 07:41
149

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();
Adorjan Princz
  • 11,708
  • 3
  • 34
  • 25
  • 56
    Does not work with all timezones. There is a good reason why getTimeZoneOffset is in minutes ! http://www.geographylists.com/list20d.html – siukurnin Sep 19 '13 at 08:28
  • 5
    @siukurnin. so to manage weird timezone, use newDate.setTime(date.getTime()+date.getTimezoneOffset()*60*1000) – Guillaume Gendre Sep 23 '13 at 14:34
  • 20
    newDate.setMinutes(date.getMinutes() - date.getTimezoneOffset()) would be enough. In corrects hours as well – Ilya Serbis Oct 23 '13 at 14:10
  • i am in IST timezone, all other answers are giving 1 hour difference in conversion.ex: localtime here is 18:00, but other answers showing it 19:00 after conversion. Only this answer giving right time. Any explanation please ? – Dashrath Nov 12 '14 at 12:46
  • 1
    Sorry, but this answer is flawed on a few points. 1. Shifting the time by the amount of the offset will not change the time zone of the `Date` object. Data errors will appear where the value is near DST transitions of the local time zone. 2. A `Date` object is internally *already* in UTC. It's only when you use the non-UTC functions on it that it converts to the local time zone. So there's no such thing as a UTC Date object vs a Local Date object. – Matt Johnson-Pint Mar 05 '16 at 06:37
  • 1
    3. If the input was UTC, then all points should be valid and unambiguous. But here, when you parse it with the `Date` object constructor, you're treating it as local time, so values in the DST spring-forward gap will be adjusted erroneously. – Matt Johnson-Pint Mar 05 '16 at 06:37
  • 1
    Pretty certain this can't possibly work for any time zone which is 30 minutes out? It seems to round to whole hours. – NickG Apr 20 '16 at 16:14
  • 7
    This also doesn't seem to set the date properly when the timezone shift crosses midnight; possibly because it it's only using setHours which doesn't affect the date? – Uniphonic Apr 07 '17 at 19:37
  • 1
    Adelaide, why do you vex me? – MrBoJangles Jun 12 '18 at 16:53
  • @Uniphonic Have you tried it? [It will handle that just fine](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours#description). `date.setHours(-25)` will set the date to be in the 11pm hour, two days ago. – maxathousand Mar 04 '22 at 16:56
  • 1
    This solution has actually a bug, a possible date change is not considered at all. – organicData Oct 18 '22 at 11:14
  • Why on earth isn't the solution just to reduce the offset to milliseconds and just add it to the epoch timestamp? i.e. const addOffset = (dt: Date, offset: number):Date => new Date(dt.valueOf() + offset * 60 * 60 * 1000. – Sean Coley May 11 '23 at 05:22
78

For me above solutions didn't work.

With IE the UTC date-time conversion to local is little tricky. 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.

var createdDateTime = new Date('2018-02-15T05:37:26.007' + 'Z');
Vladimir M
  • 4,403
  • 1
  • 19
  • 24
PramodB
  • 789
  • 5
  • 2
47

This works for me:

function convertUTCDateToLocalDate(date) {
    var newDate = new Date(date.getTime() - date.getTimezoneOffset()*60*1000);
    return newDate;   
}
Molp Burnbright
  • 659
  • 6
  • 5
46

You should get the (UTC) offset (in minutes) of the client:

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

And then do the correspondent adding or substraction to the time you get from the server.

Hope this helps.

Nobita
  • 23,519
  • 11
  • 58
  • 87
27

Put this function in your head:

<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:

document.write(d.toString().replace(/GMT.*/g,""));
Ben Bryant
  • 3,074
  • 1
  • 21
  • 13
19

This is a simplified solution based on Adorjan Princ´s answer:

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));
Daniel Tonon
  • 9,261
  • 5
  • 61
  • 64
huha
  • 4,053
  • 2
  • 29
  • 47
  • Why was this downvoted on Oct 9 2017? Please write a comment to help me understand your opinion. – huha Oct 13 '17 at 07:44
  • Why do you have to convert the date to new Date twice? Once when you call the function and a second time in the function? – Sofía May 20 '21 at 09:55
  • @Sofia You are right. It's not really needed. I played around on [wschools](https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_date_obj) now and a simpified version also works. Maybe the duplicate `new Date(...)` came from debugging. – huha May 21 '21 at 10:55
  • I thought it was a necessary hack, thanks for clearing that up : ) – Sofía May 21 '21 at 12:11
  • 1
    The "simpler" solution is not the better solution. It mutates the original date. The first option provided is the one you should use. – Daniel Tonon Sep 23 '21 at 00:56
17

if you have

"2021-12-28T18:00:45.959Z" format

you can use this in 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" (e.g. "fa-IR").


also you can use options for toLocaleTimeString like { 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

Marzieh Mousavi
  • 1,213
  • 1
  • 12
  • 28
16

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:

convertLocalDatetoUTCDate: function(date){
    return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(),  date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
}
Uniphonic
  • 845
  • 12
  • 21
  • 3
    Less code to use `new Date(+date + date.getTimezoneOffset() * 6e4)`. ;-) – RobG Sep 21 '18 at 11:17
  • it wont work , my time in utc is "2020-04-02T11:09:00" , so tried this from Singapore , new Date(+new Date("2020-04-02T11:09:00") + new Date("2020-04-02T11:09:00").getTimezoneOffset() * 6e4) , giving wrong time – AhammadaliPK Apr 02 '20 at 11:51
  • this worked , new Date("2020-04-02T11:09:00" + 'Z'); – AhammadaliPK Apr 02 '20 at 11:53
14

Use this for UTC and Local time convert and vice versa.

//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;
}
Marzieh Mousavi
  • 1,213
  • 1
  • 12
  • 28
14

Add the time zone at the end, in this case '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

theDate.toLocaleString();  // "6/29/2011, 9:52:48 AM"
theDate.toLocaleTimeString();  // "9:52:48 AM"
theDate.toLocaleDateString();  // "6/29/2011"
pabloa98
  • 630
  • 7
  • 16
11

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:

    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)
MaurGi
  • 1,698
  • 2
  • 18
  • 28
  • this is converting to local timeZone , how can we convert to specific timezone without plus or minus in date value ? – Kishor Jun 18 '21 at 06:05
10

In case you don't mind usingmoment.js and your time is in UTC just use the following:

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:

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');
adnan kamili
  • 8,967
  • 7
  • 65
  • 125
6

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)

mizuki nakeshu
  • 1,315
  • 2
  • 9
  • 12
  • Does anyone have any issues with this? This seems like the best option for me. I took a UTC string which had "(UTC)" at the end of it, set it up as a Date object using `new Date('date string')`, and then added these two lines and it seems to be coming back with a time based completely off the server's UTC timestamp with adjustments made to make it match the user's local time. I do have to worry about the weird fractions-of-an-hour timezones too... Not sure if it holds up perfectly all the time... – tylerl Aug 22 '16 at 17:22
  • tried many other options, none of them worked, But this is working – Sameera K May 17 '19 at 04:49
6

This is what I'm doing to convert UTC to my Local Time:

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).

TLVF2627
  • 97
  • 2
  • 8
  • You have errors in your variable names... And maybe better to convert your code to Code snippet, so we can run and test? – Anton Sep 15 '20 at 16:58
  • @Anton thank you for remind me. I've added Code snippet and fixed my code. – TLVF2627 Sep 27 '20 at 12:47
5

Using YYYY-MM-DD hh:mm:ss format :

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.

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
  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 represent the offset from the UTC timezone.
Gudradain
  • 4,653
  • 2
  • 31
  • 40
5

A JSON date string (serialized in C#) looks like "2015-10-13T18:58:17".

In angular, (following Hulvej) make a localdate filter:

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' }}
James Howey
  • 51
  • 1
  • 1
5

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();
}
C.Lee
  • 10,451
  • 9
  • 31
  • 46
3

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 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.

Nisarg Desai
  • 361
  • 3
  • 16
3

@Adorojan's answer is almost correct. But addition of offset is not correct since offset value will be negative if browser date is ahead of GMT and vice versa. 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);
}
Sastrija
  • 3,284
  • 6
  • 47
  • 64
2

using dayjs library:

(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.)

ToniG
  • 111
  • 1
  • 5
2

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"

With this format It doesnt really know if its a local format or a UTC time. So since we know that the date is a UTC we have to make sure that JS will know that its a UTC. So we have to set the date as 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. Mostly servers timestampz format are in ISO-8601 ex: '2011-06-29T16:52:48.000Z'. With this we can just pass it to the date function and toLocaleString() function.

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

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):

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>
Moriz
  • 11
  • 2
1

You can use momentjs ,moment(date).format() will always give result in local date.

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

AConsumer
  • 2,461
  • 2
  • 25
  • 33
1

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:

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

this worked well for me with safari/chrome/firefox :

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

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.

SJMiller
  • 11
  • 2
1

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

The source string must specify a time zone or UTC.

One-liner:

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

Result in one of my web browsers:

"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)"
John Pick
  • 5,562
  • 31
  • 31
0

In Angular I used Ben's answer this way:

$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:

{{ date_expression | date : format : timezone}}

Angular 1.4.3 Date API

Klik
  • 1,757
  • 1
  • 21
  • 38
Post Impatica
  • 14,999
  • 9
  • 67
  • 78
0

I wrote a nice little script that takes a UTC epoch and converts it the client system timezone and returns it in d/m/Y H:i:s (like the PHP date function) format:

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;

};
John Bell
  • 2,350
  • 1
  • 14
  • 23
0

I've created one function which converts all the timezones into local time.

I did not used getTimezoneOffset(), because it does not returns proper offset value

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"
Rohit Parte
  • 3,365
  • 26
  • 26
0

UTC to local to ISO - Using Molp Burnbright answer

because server only accepts ISO date-time so I converted UTC to my local timezone and sent it to server in ISO format

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()

Suvesh
  • 61
  • 1
  • 5
0

I had a similar problem, I used following code code (JavaScript) to convert UTC to local time

let a = new Date()
a = a.getFullYear().toString() + "-" + (a.getMonth() + 1).toString().padStart(2, "0") + "-" + a.getDate().toString().padStart(2, "0")
console.log(a)
Abdullah Ansari
  • 618
  • 1
  • 4
  • 10
0

If your want to convert UTC to any time zone, I am giving example of IST

const istOffsetMinutes = 330 ( IST offset in minutes (5 hours and 30 minutes))

const istDate = new Date(date.getTime() + istOffsetMinutes * 60 * 1000);
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
-1
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.

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. Since offset returned is calculated with DST (correct me if I am wrong), so it will set that time back in the variable "utc". Finally return the date object.

Dapu
  • 195
  • 1
  • 3
  • 13
-1

You can get it done using moment.js file.

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

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

For the TypeScript users, here is a helper 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;
};
jefelewis
  • 1,850
  • 1
  • 27
  • 63
-1

In JavaScript I used:

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

{{updaated_time | date: 'dd-MM-yyyy HH:mm'}} //output: 26-10-2022 12:00
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Yogeshraja
  • 35
  • 2