Amr Elgarhy
Amr Elgarhy

Reputation: 68892

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. I want to convert it to the current user’s browser time zone using JavaScript.

How this can be done using JavaScript or jQuery?

Upvotes: 565

Views: 1292336

Answers (30)

Molp Burnbright
Molp Burnbright

Reputation: 729

This works for me:

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

Upvotes: 52

Denys Sokolov
Denys Sokolov

Reputation: 83

var d = new Date(Date.parse('6/29/2011 4:52:48 PM'));
d.setMinutes(d.getMinutes() - d.getTimezoneOffset());

My local time:

Wed Jun 29 2011 18:52:48 GMT+0200 (Central European Summer Time)

To check the free tool: UTC to Local Time Converter enter image description here

Upvotes: 0

Mrudula nemani
Mrudula nemani

Reputation: 1

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

Upvotes: 0

Marzieh Mousavi
Marzieh Mousavi

Reputation: 1624

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

Upvotes: 19

Yogeshraja
Yogeshraja

Reputation: 29

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

Upvotes: -4

user3560410
user3560410

Reputation:

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

Upvotes: 15

Jenuel Ganawed
Jenuel Ganawed

Reputation: 384

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

Upvotes: 3

Suvesh
Suvesh

Reputation: 71

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

Upvotes: 0

huha
huha

Reputation: 4245

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

Upvotes: 22

ToniG
ToniG

Reputation: 111

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

Upvotes: 2

John Pick
John Pick

Reputation: 5650

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

Upvotes: 1

jefelewis
jefelewis

Reputation: 2049

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

Upvotes: -1

TLVF2627
TLVF2627

Reputation: 97

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

Upvotes: 6

SJMiller
SJMiller

Reputation: 11

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.

Upvotes: 1

hamila firas
hamila firas

Reputation: 11

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

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

Upvotes: 1

Suraj Galande
Suraj Galande

Reputation: 11

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;

Upvotes: 1

Rohit Parte
Rohit Parte

Reputation: 4016

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"

Upvotes: 0

REvathY M
REvathY M

Reputation: 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');

Upvotes: -1

C.Lee
C.Lee

Reputation: 11249

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

Upvotes: 5

AConsumer
AConsumer

Reputation: 2771

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

Upvotes: 1

Sastrija
Sastrija

Reputation: 3374

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

Upvotes: 3

pabloa98
pabloa98

Reputation: 618

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"

Upvotes: 15

PramodB
PramodB

Reputation: 869

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');

Upvotes: 86

Post Impatica
Post Impatica

Reputation: 16373

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

Upvotes: 0

Dapu
Dapu

Reputation: 315

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.

Upvotes: -1

Uniphonic
Uniphonic

Reputation: 865

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

Upvotes: 17

John Bell
John Bell

Reputation: 2350

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;

};

Upvotes: 0

adnan kamili
adnan kamili

Reputation: 9445

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');

Upvotes: 10

Hulvej
Hulvej

Reputation: 4185

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.

Upvotes: 304

James Howey
James Howey

Reputation: 51

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

Upvotes: 5

Related Questions