[英]Convert date string to date with timezone using moment timezone js
我需要將日期字符串轉換為PDT(太平洋夏令時間),並且必須在當地時間顯示還原日期時間。
我嘗試過
console.log(moment.tz("16:23:42 Sep 27, 2018 PDT", 'HH:mm:ss MMM DD, YYYY PDT',"PDT").format());
當我運行上面的代碼時,它將顯示
2018-09-27T16:23:42Z
不是當地時間。 等效的本地時間必須不同。 如何獲取指定日期字符串的本地時間。
換句話說,我的意思是這樣說https://forums.asp.net/t/1552114.aspx?Convert+Datetime+String+from+PDT+to+IST+local+time+datetime+string
您可以執行以下操作:
var desiredFormat = "HH:mm:ss MMM DD, YYYY";
var timeToBeConverted = moment("16:23:42 Sep 27, 2018", desiredFormat);
var timeZone = "America/Los_Angeles";
console.log(timeToBeConverted.tz(timeZone).format(desiredFormat) + " PDT");
您提供的時區不能為“ PDT”。 如果您在控制台中使用moment.tz.names()
,將獲得有效時區名稱的列表。 在上面的示例中,我使用了“ America / Los_Angeles”,但是任何觀察PDT的區域都可以。
您可以嘗試一下,我認為它將起作用
首先獲取時區偏移量timeZoneId
是您的時區。
const offset = moment['tz'](moment(new Date()), timeZoneId).utcOffset() * 60000;
其次根據您的日期和偏移量創建新日期
console.log(new Date(new Date(yourDateString).getTime() + offset))
是的, yourDateString
是您的日期字符串,更適合日期obj,但w / e
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.