Home > Web Front-end > JS Tutorial > How Can I Convert UTC Date and Time to a User's Local Browser Time Zone Using JavaScript or jQuery?

How Can I Convert UTC Date and Time to a User's Local Browser Time Zone Using JavaScript or jQuery?

Linda Hamilton
Release: 2024-12-06 07:35:12
Original
995 people have browsed it

How Can I Convert UTC Date and Time to a User's Local Browser Time Zone Using JavaScript or jQuery?

Converting UTC Date and Time to Local Browser Time Zone

When retrieving date and time information from servers, it's often provided in Coordinated Universal Time (UTC). However, displaying these values in a user's local time zone is essential for user-friendly applications. JavaScript and jQuery offer convenient methods to achieve this conversion.

Using JavaScript to Convert UTC to Local Time

The JavaScript Date object accepts UTC-formatted strings. To convert a UTC string to the browser's local time zone, simply append "UTC" to the string before creating a new Date object:

var utcDateTime = "6/29/2011 4:52:48 PM";
var utcDate = new Date(utcDateTime + " UTC");

console.log(utcDate.toString()); // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"
Copy after login

The resulting utcDate object will represent the local time equivalent of the provided UTC string.

Using jQuery to Convert UTC to Local Time

jQuery simplifies the process even further with its utc() and local() functions:

var utcDateTime = "6/29/2011 4:52:48 PM";
var localDate = $.utc(utcDateTime).local();

console.log(localDate.format()); // "2011-06-29T09:52:48-07:00"
Copy after login

The localDate object is a moment object that provides additional time manipulation and formatting capabilities.

The above is the detailed content of How Can I Convert UTC Date and Time to a User's Local Browser Time Zone Using JavaScript or 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