【问题标题】:Convert Date to UTC with timezone使用时区将日期转换为 UTC
【发布时间】:2021-03-12 10:42:40
【问题描述】:

我正在迁移我的数据库中的一些数据,并将日期作为字符串"date" : "2020-10-23",。我想将该日期转换为日期时间对象以将其存储在另一个字段中。我正在使用luxon

let DateTime = luxon.DateTime;

// Function
function timeZoneToUTC(timezone, year, month, day, hours) {
  const dateObj = `${year}-${month}-${day} ${hours}:00`;
  let date = DateTime.fromFormat(dateObj, 'yyyy-M-d H:mm', {
    zone: timezone
  });
  return date.toUTC().toString();
}

// Example
let record = {preparationTime: "18",
              date : "2020-10-23"};
let dateISO = DateTime.fromISO(record.date, {zone: 'Europe/Amsterdam'});
dateISO = dateISO.minus({days: 1});
let year = dateISO.year;
let month = dateISO.month;
let day = dateISO.day;

record.newOrderTime = timeZoneToUTC('Europe/Amsterdam', year, month, day, 22);

console.log(record.newOrderTime);
<script src = "https://cdn.jsdelivr.net/npm/luxon@1.25.0/build/global/luxon.min.js" > </script>

上面的代码返回了错误的时间,例如:2020-10-23 将是2020-10-22T20:00:00.000Z 日期正确但时间不正确,应该是 21 而不是 20

【问题讨论】:

  • 2020-10-23T00:00:00 in Amsterdam 是 2020-10-22T22:00:00Z,即早两个小时,因为该日期阿姆斯特丹的偏移量是 +2 小时(夏令时在阿姆斯特丹,CEDT)。 10 月 25 日星期日 03:00 时,偏移量变为 +1(阿姆斯特丹标准时间,CEST)。

标签: javascript date datetime luxon


【解决方案1】:
猜你喜欢
  • 2017-11-07
  • 2011-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-02
  • 2019-09-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多