Home >Web Front-end >JS Tutorial >How to Convert UTC Date-Time to Local Date-Time in JavaScript and jQuery?

How to Convert UTC Date-Time to Local Date-Time in JavaScript and jQuery?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-14 12:36:11919browse

How to Convert UTC Date-Time to Local Date-Time in JavaScript and jQuery?

Converting UTC Date-Time to Local Date-Time

When receiving a datetime variable in UTC format from a server, such as "6/29/2011 4:52:48 PM", it is often necessary to convert it to the user's local time zone for display purposes. This can be achieved using JavaScript or jQuery.

Using JavaScript

To convert a string representation of a datetime in UTC time to the user's local time zone using JavaScript, append 'UTC' to the string before converting it to a date:

var date = new Date('6/29/2011 4:52:48 PM UTC');

This will create a Date object that represents the date and time in the user's local time zone. The toString() method of the Date object can be used to get the date and time in a string format for display:

date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"

Using jQuery

jQuery provides a similar method for converting a UTC datetime to a local datetime. The moment-timezone library must be included in the document for this to work:

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.18/moment-timezone.min.js"></script>

With the moment-timezone library loaded, you can use the following jQuery code to convert a UTC datetime string to the user's local time zone:

var date = moment.utc('6/29/2011 4:52:48 PM').local().format('MM/DD/YYYY HH:mm:ss a');

This will create a date object that represents the date and time in the user's local time zone. The format() method of the moment object can be used to get the date and time in a string format for display.

The above is the detailed content of How to Convert UTC Date-Time to Local Date-Time in JavaScript and jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn