Javascript date utc to local

Javascript date utc to local

Last updated: Jan 12, 2023
Reading time · 7 min

banner

# Table of Contents

# Convert UTC/GMT to local time using JavaScript

Use the Date() constructor to convert UTC/GMT to local time.

Passing a date and time string in ISO 8601 format to the Date() constructor converts the UTC date and time to local time.

Copied!
// 👇️ Example date and time in UTC const utcDate = '2022-01-15T11:02:17Z'; const date = new Date(utcDate); // 👇️ "Sat Jan 15 2022 13:02:17 GMT+0200 (Eastern European Standard Time)" console.log(date); // ✅ Convert to Local time console.log(date.toLocaleString()); // 👉️ "1/15/2022, 1:02:17 PM"

convert utc gmt to local time

Note that GMT and UTC share the same current time.

The difference between them is that GMT is a time zone, whereas UTC is a time standard and is the basis for time zones worldwide.

UTC and GMT don’t change for Daylight Saving Time (DST) and always share the same current time.

Passing a date and time string in ISO 8601 format to the Date() constructor converts the UTC/GMT date and time to local time.

The time in the UTC string from the example shows 11:02:17 UTC . Since my time zone is UTC +0200, the result shows 13:02:17 .

Note that the UTC date time string should end with a Z to be considered valid ISO 8601.

If the string doesn’t have a Z at the end, add it using the addition operator, e.g. isoStr + ‘Z’ .

You can also get an ISO 8601 date time string by calling the toISOString() method on a Date object.

Copied!
// 👇️ "2023-07-25T12:51:25.173Z" console.log(new Date().toISOString());

We used the toLocaleString method to convert UTC to locale time in the example.

When no parameters are passed to the method, it returns a string that is formatted according to the user’s default locale and time zone.

Copied!
const utcDate = '2022-01-15T11:02:17Z'; const date = new Date(utcDate); // ✅ Convert to Local time console.log(date.toLocaleString()); // 👉️ "1/15/2022, 1:02:17 PM"

The comments above illustrate the formatting if the methods are run with a time zone of Eastern European Standard Time.

The output you see will likely be different and depends on your default locale and default time zone.

# Get date and time components according to local time

You can use any of the get* methods to get any of the date and time components of a date according to the visitor’s local time.

All of the methods in the code sample below return the date or time component according to the visitor’s time zone and will yield different results when accessed in different time zones.

Copied!
// 👇️ Example date and time in UTC const utcDate = '2022-01-15T11:02:17Z'; const date = new Date(utcDate); // 👇️ returns Hour of the date console.log(date.getHours()); // 👉️ 13 // 👇️ returns Minutes of the date console.log(date.getMinutes()); // 👉️ 2 // 👇️ returns Seconds of the date console.log(date.getSeconds()); // 👉️ 17 // 👇️ returns year of the date console.log(date.getFullYear()); // 👉️ 2022 // 👇️ returns month (0-11) // 0 is January, 11 is December console.log(date.getMonth()); // 👉️ 0 // 👇️ returns day of the month (1-31) console.log(date.getDate()); // 👉️ 15

get date and time components according to local time

All of the get* methods return the date or time component according to the visitor’s local date and time.

Читайте также:  Html table row with no border

Note that the Date.getMonth method returns the month of the specified date as a zero-based value (0 = January, 1 = February, etc.)

If you need a complete list of the Date.get* methods, visit the MDN docs.

You can use these methods to format the local date and time in many different ways.

Here is an example that formats the local date and time as YYYY-MM-DD hh:mm:ss .

Copied!
function padTo2Digits(num) return num.toString().padStart(2, '0'); > function formatDate(date) return ( [ date.getFullYear(), padTo2Digits(date.getMonth() + 1), padTo2Digits(date.getDate()), ].join('-') + ' ' + [ padTo2Digits(date.getHours()), padTo2Digits(date.getMinutes()), padTo2Digits(date.getSeconds()), ].join(':') ); > // 👇️ 2022-01-15 13:02:17 (yyyy-mm-dd hh:mm:ss) const utcDate = '2022-01-15T11:02:17Z'; console.log(formatDate(new Date(utcDate)));

We joined the date components of the date with a hyphen separator and the time components with a colon separator.

You could reorder the date components, change the separator to a forward slash / or tweak this function in any way that suits your use case.

Note that most likely, you shouldn’t be storing local dates and times in your database.

For consistency, you should mostly use local time when you have to render a date and time to the user, but you should store the actual values in UTC.

For example, if you store a local time of midnight (00:00) in your database, you wouldn’t know if that’s midnight in Tokyo (Japan), Paris (France), in New York (US), etc. These are all different moments that are hours apart.

There is a UTC equivalent for all of the get* methods we previously covered.

All of the getUTC* methods return the date or time component according to universal time.

If you need a complete list of the getUTC* methods, visit the MDN docs.

The getUTC* methods return the date or time component according to universal time, whereas the get* methods return them according to local time (the time zone the visitor’s computer is in).

The get* methods return different results depending on where the user visits your site from.

# Convert local time to UTC using JavaScript

Use the toUTCString() method to convert local time to UTC/GMT.

The toUTCString() method converts a date to a string, using the UTC time zone.

Copied!
const date = new Date(); // 👇️ 2023-07-25T12:53:16.133Z console.log(date); const utcStr = date.toUTCString(); console.log(utcStr); // 👉️ "Tue, 25 Jul 2023 12:53:16 GMT" // 👇️ "12:53:16" console.log( [ padTo2Digits(date.getUTCHours()), padTo2Digits(date.getUTCMinutes()), padTo2Digits(date.getUTCSeconds()), ].join(':'), ); function padTo2Digits(num) return num.toString().padStart(2, '0'); >

convert local time to utc

We used the toUTCString to convert a local time to UTC.

The toUTCString() method returns a string that represents the given date using the UTC time zone.

The results from the code snippets above show GMT.

The difference between them is that GMT is a time zone, whereas UTC is a time standard and is the basis for time zones worldwide.

The date variable stores the date in my local time, which is UTC+0200.

When I convert the date and time to UTC, I get a result that is 2 hours behind because my time zone (Eastern European Standard Time) is 2 hours behind UTC.

If you need a new Date object with the UTC time instead of a string, use this approach instead.

Copied!
const localDate = new Date(); const utcDate = new Date(localDate.toUTCString().slice(0, -4)); console.log(utcDate);

We basically sliced off the GMT part of the string and passed the result to the Date() constructor.

You could also use the toISOString() method to get a string in the ISO 8601 format of YYYY-MM-DDTHH:mm:ss.sssZ .

The Z at the end of the format means UTC, that is, an offset from UTC of zero hours, minutes and seconds.

Copied!
const date = new Date(); const isoStr = date.toISOString(); console.log(isoStr); // 👉️ "2022-01-15T14:49:31.612Z"

The toISOString method returns a string representing the date in the ISO 8601 format, according to universal time.

If you only need the time in UTC, you can use the following function, which formats the UTC time as hh:mm:ss .

Copied!
const date = new Date(); function padTo2Digits(num) return num.toString().padStart(2, '0'); > function getGMTTime(date = new Date()) return [ padTo2Digits(date.getUTCHours()), padTo2Digits(date.getUTCMinutes()), padTo2Digits(date.getUTCSeconds()), ].join(':'); > console.log(getGMTTime()); // 👉️️ "14:49:31"

We created a reusable function that returns the time in GMT, formatted as hh:mm:ss .

The function takes a Date object by default, but if one isn’t provided it returns the current UTC time.

The getUTCHours method returns the hour (0 — 23) in the specified date, according to universal time.

The getUTCMinutes method returns the minutes (0 — 59) in the date, according to universal time.

The getUTCSeconds method returns the seconds (0 — 59) in the date, according to universal time.

In the function, we made sure to display the hours, seconds and minutes as 2 digits, even when they are less than 10 .

By default, if any of the values is less than 10 , the methods return a single digit, which is not what we want.

We padded the results if necessary and joined them with a colon separator.

You can adjust this depending on your use case, e.g. include the year, month, day of the month values in the formatted string.

All of the getUTC* methods return the date or time component according to universal time.

Copied!
const date = new Date(); // 👉️ "Sat Jan 15 2022 16:05:47 GMT+0200" console.log(date); // 👇️ returns UTC year of the date console.log(date.getUTCFullYear()); // 👉️ 2022 // 👇️ returns UTC month (0-11) // 0 is January, 11 is December console.log(date.getUTCMonth()); // 👉️ 0 // 👇️ returns UTC day of the month (1-31) console.log(date.getUTCDate()); // 👉️ 15 // 👇️ returns UTC Hour of the date console.log(date.getUTCHours()); // 👉️ 14 // 👇️ returns UTC Minutes of the date console.log(date.getUTCMinutes()); // 👉️ 5 // 👇️ returns UTC Seconds of the date console.log(date.getUTCSeconds()); // 👉️ 47

Note that the getUTCMonth method returns the month of the specified date as a zero-based value (0 = January, 1 = February, etc.)

Here is an example that uses the getUTC* methods to format a Date as YYYY-MM-DD hh:mm:ss .

Copied!
function padTo2Digits(num) return num.toString().padStart(2, '0'); > function formatDate(date) return ( [ date.getFullYear(), padTo2Digits(date.getUTCMonth() + 1), padTo2Digits(date.getUTCDate()), ].join('-') + ' ' + [ padTo2Digits(date.getUTCHours()), padTo2Digits(date.getUTCMinutes()), padTo2Digits(date.getUTCSeconds()), ].join(':') ); > // 👇️ "2022-12-17 14:57:28" console.log(formatDate(new Date()));

We created a reusable function that formats the date and time as YYYY-MM-DD hh:mm:ss using the UTC time standard.

You could reorder the date components, change the separator to a forward slash / , or make any other changes that suit your use case.

There is a non-UTC equivalent for each of these methods, for example getUTCFullYear vs Date.getFullYear.

The getUTC* methods return the date or time component according to universal time, whereas the get* methods return them according to local time (the time zone the visitor’s computer is in).

The get* methods return different results depending on where the user visits your site from.

For example, if you store a local time of midnight (00:00) in your database, you wouldn’t know if that’s midnight in Tokyo (Japan), Paris (France), in New York (US), etc. These are all different moments that are hours apart.

For consistency, you should mostly use local time when you have to render a date and time to the user, but store the actual values in UTC.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Convert UTC to Local Time in JavaScript

Convert UTC to Local Time in JavaScript

  1. Use the tostring() Function to Convert UTC to Local Time in JavaScript
  2. Use the Date() Method to Convert UTC to Local Time in JavaScript

This tutorial demonstrates how to convert UTC to local time in JavaScript.

Use the tostring() Function to Convert UTC to Local Time in JavaScript

JavaScript allows us to convert the UTC to local time with the help of a method known as toString() .

var dt = new Date('7/24/2021 2:11:55 PM UTC'); console.log(dt.toString()) 
"Sat Jul 24 2021 16:11:55 GMT+0200 (Central European Summer Time)" 

In the above example, the final date and time are based on the local time zone. The variable dt consists of the user-specified date-time in UTC in a Date object.

Use the Date() Method to Convert UTC to Local Time in JavaScript

We create objects to store date using the Date() method in JavaScript. When we store the date in ISO 8601 format, the server returns the date and time based on the local time zone.

var dt = new Date('2021-07-24T20:37:26.007' + 'Z'); console.log(dt.toLocaleString()); 

Related Article — JavaScript DateTime

Источник

Оцените статью