[英]Javascript to convert UTC to local time
好的,假設 JSON 解析字符串 UTC 日期如下:
2012-11-29 17:00:34 UTC
現在,如果我想將這個 UTC 日期轉換為我的本地時間,我該怎么做呢?
如何將其格式化為yyyy-MM-dd HH:mm:ss z
類的格式?
這個date.toString('yyyy-MM-dd HH:mm:ss z');
從不鍛煉:/
嘗試:
var date = new Date('2012-11-29 17:00:34 UTC');
date.toString();
var offset = new Date().getTimezoneOffset();
offset
將是從本地時間到 UTC 的時間間隔(以分鍾為單位)。 要從 UTC 日期獲取當地時間,您需要從日期中減去分鍾數。
utc_date.setMinutes(utc_date.getMinutes() - offset);
要格式化您的日期,請嘗試以下功能:
var d = new Date();
var fromatted = d.toLocaleFormat("%d.%m.%Y %H:%M (%a)");
但這樣做的缺點是,它是一個非標准功能,在 Chrome 中不起作用,但在 FF (afaik) 中起作用。
克里斯
上面的解決方案是正確的,但可能會在 FireFox 和 Safari 中崩潰! 這就是webility.js試圖解決的問題。 檢查toUTC
功能,它適用於大多數主要瀏覽器,並以 ISO 格式返回時間
您可以查看date-and-time api 以輕松進行日期操作。
let now = date.format(new Date(), 'YYYY-MM-DD HH:mm:ss', true); console.log(now);
<script src="https://cdn.jsdelivr.net/npm/date-and-time/date-and-time.min.js"></script>
這是輸出 mm/dd/yy 的另一個選項:
const date = new Date('2012-11-29 17:00:34 UTC');
date.toLocaleString();
//output 11/29/2012
這應該工作
var date = new Date('2012-11-29 17:00:34 UTC');
date.toString()
這適用於Chrome和Firefox 。
未在其他瀏覽器上測試。
const convertToLocalTime = (dateTime, notStanderdFormat = true) => { if (dateTime !== null && dateTime !== undefined) { if (notStanderdFormat) { // works for 2021-02-21 04:01:19 // convert to 2021-02-21T04:01:19.000000Z format before convert to local time const splited = dateTime.split(" "); let convertedDateTime = `${splited[0]}T${splited[1]}.000000Z`; const date = new Date(convertedDateTime); return date.toString(); } else { // works for 2021-02-20T17:52:45.000000Z or 1613639329186 const date = new Date(dateTime); return date.toString(); } } else { return "Unknown"; } }; // TEST console.log(convertToLocalTime('2012-11-29 17:00:34 UTC'));
// d = "2021-09-23T15:51:48.31"
console.log(new Date(d + "z").toLocaleDateString()); // gives 9/23/2021
console.log(new Date(d + "z").toLocaleString()); // gives 9/23/2021, 10:51:48 AM
console.log(new Date(d + "z").toLocaleTimeString()); // gives 10:51:48 AM
/*
* convert server time to local time
* simbu
*/
function convertTime(serverdate) {
var date = new Date(serverdate);
// convert to utc time
var toutc = date.toUTCString();
//convert to local time
var locdat = new Date(toutc + " UTC");
return locdat;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.