簡體   English   中英

moment.utc(date).local()仍然提供utc時間。

[英]moment.utc(date).local() still gives utc time.

我正在從數據庫中獲取格式為2017-06-28 23:24:17.1-07並且嘗試使用時間將其轉換為本地時間,但我仍在獲取UTC時間。

這是我插入控制台的模擬版本:

var now = new Date(); // Fri Jun 30 2017 15:45:30 GMT-0700 (PDT)

// simulate date received from server
var now_utc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(),  now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds()); // Fri Jun 30 2017 22:45:41 GMT-0700 (PDT);

var local = moment.utc(now_utc).local().format('LLL') // "June 30, 2017 10:45 PM"

^ should be ~3:45pm.

如您所見, local的輸出與now_utc的輸入相同。

我正在從數據庫中獲取2017-06-28 23:24:17.1-07格式的時間戳,並且我正在嘗試使用矩將其轉換為本地時間...

這是直接從數據庫中獲取的非常不尋常的字符串格式,但是如果確實是您擁有的字符串,則:

// parse the input string
var m = moment("2017-06-28 23:24:17.1-07", "YYYY-MM-DD HH:mm:ss.SZ");

// format the output string
var s = m.format("LLL");

根本不需要使用Date對象,也不需要調用.local()因為local-mode是默認的,並且您要提供偏移量。

我遇到過同樣的問題。 盡管我無法理解為什么.local()無法正常工作,但使用moment-timezone解決了我的問題。

嘗試如下修改本地變量:

var local = moment.utc(now_utc).tz(時區).format('LLL')

您可以在此處找到所需的時區值

PS不要忘了安裝moment-timezone軟件包。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM