首頁 > web前端 > js教程 > 主體

如何將 UTC 紀元時間戳轉換為本地日期?

Susan Sarandon
發布: 2024-11-15 07:00:02
原創
991 人瀏覽過

How to Convert UTC Epoch Timestamps to Local Dates?

Convert UTC Epoch to Local Date

Problem

Converting a UTC epoch timestamp into a local date object can be challenging. The standard Date() constructor interprets epochs as local, leading to incorrect results when the timestamp is actually in UTC. Attempts to create a UTC object and adjust the time using setTime() or retrieve the UTC offset have proven unsuccessful.

Solution

A simpler solution exists to convert UTC epochs to local dates. Instead of manipulating dates directly, set a new date to the epoch (represented as 0) and add the UTC epoch units. For instance, to convert a UTC epoch in seconds (e.g., 1234567890) to a local time:

var utcSeconds = 1234567890;
var d = new Date(0); // Sets the date to the epoch
d.setUTCSeconds(utcSeconds);
登入後複製

The resulting date, d, will now represent the local time equivalent of the UTC epoch timestamp. In this example, the date would be: Fri Feb 13 2009 18:31:30 GMT-0500 (EST).

以上是如何將 UTC 紀元時間戳轉換為本地日期?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板