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

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

Susan Sarandon
Susan SarandonOriginal
2024-12-22 18:37:09819browse

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

Converting UTC Date Time to Local Date Time

When receiving a datetime variable from the server in UTC format, the need arises to convert it to the current user's browser time zone for accurate display. This guide provides a JavaScript or jQuery-based solution for this task.

JavaScript Conversion

To convert a UTC datetime string in JavaScript, follow these steps:

  1. Append the string 'UTC' to the original datetime:

  2. Create a new Date object using the modified string:

  3. The resulting date object will represent the local time equivalent of the original UTC datetime.

Example:

utcDateTime = '6/29/2011 4:52:48 PM UTC';
date = new Date(utcDateTime);
The output `Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)` represents the local time in the user's browser, corresponding to 4:52:48 PM UTC.

**jQuery Conversion**

jQuery provides a similar method for UTC datetime conversion:

>```
var date = $.datepicker.parseDate('utc', '6/29/2011 4:52:48 PM UTC');

The resulting date variable will contain the local time equivalent of the UTC datetime.

Note: The example shown assumes the user's time zone is Pacific Daylight Time (PDT). The actual local time displayed will vary based on the user's browser time zone settings.

The above is the detailed content of How to Convert UTC Date and Time to Local 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