在我的Node.js應用程序中,用戶提交日期,時間和時區(單獨的表單字段)。使用Moment Timezone,我試圖保存調整爲無偏移的日期(與時區無關)。Moment JS - 將用戶提交的日期/時間/時區轉換爲與時區無關的UTC
下面的代碼工作,但有一個更簡單/更清潔的方式來實現相同的結果?有乘以抵消-1似乎hackish的:
const userDate = new Date(req.body.date + ' ' + req.body.time);
const userTz = req.body.tz;
const offset = moment.tz(userTz).utcOffset();
const utc = moment(userDate).utcOffset(-1*offset).format('YYYY-MM-DD[T]HH:mm:ss');
例輸入:
Date: 09/06/2016 (via Bootstrap date picker)
Time: 07:41:00 (via Bootstrap time picker)
Timezone: America/New_York (UTC/GMT -4 hours)
返回(正確):
2016-09-06T11:41:00Z
提前感謝!
moment.js,你可以使用UTC變種。例如。 moment.utc() - > http://momentjs.com/docs/#/parsing/utc/ – Keith
如何使用沒有原始時區知識的.utc()正確調整偏移量? –
未經測試。你可以鏈接像時刻(userDate).tz(userTz).utc()。格式('YYYY-MM-DD HH:mm:ss') – Veeram