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
Release: 2024-12-14 12:36:11
Original
917 people have browsed it

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');
Copy after login

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)"
Copy after login

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>
Copy after login

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');
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template