【问题标题】:How can I get the ISO format for date and time in javascript?如何在 javascript 中获取日期和时间的 ISO 格式?
【发布时间】:2020-12-08 07:43:17
【问题描述】:

我有两个单独的日期和时间字段:-

const date = 2020-12-10;
const time = 22:00;

预期输出:-

2020-12-10T10:00:00Z

我正在遵循这种方法,但时间错了:-

const date = DateUtil.getFullDateString(this.state.date_value);
const time = moment(this.state.time_value, ['HH.mm']).format('hh:mm a');
const momentObj = moment(date + time, 'YYYY-MM-DD HH:mm');
const dateTime = momentObj.toISOString();

the output of time is coming 18:30:00 but need to have 10:00:00

2020-12-10T18:30:00Z

【问题讨论】:

  • date + "T" + time + ":00Z"?假设您的字段是 UTC,但我不太确定。
  • 字段不是UTC
  • 首先你说你希望 22:00 变成 10:00,表明你在 +12,然后你希望 18:30 但得到 10:00,表明你在 -8 :30。您将 time 格式化为“hh:mm a”(即 12 小时时间),然后将其解析为“HH:mm”(24 小时时间)。

标签: javascript date datetime momentjs iso8601


【解决方案1】:

您可以一一解析日期和时间,然后添加时间到日期,最后根据需要格式化。

const date = '2020-12-10';
const time = '22:00';

const momentDate = moment(date).utc().startOf('day'); // utc() to avoid the offset
console.log(momentDate);
const momentTime = moment(time, 'HHmm').format('HH:mm');
console.log(momentTime);
const resultTime = momentDate.add(momentTime);
console.log(resultTime);

// Format as you want
console.log(resultTime.format('LLL'));
console.log(resultTime.format('YYYY-MM-DDThh:mm:ss.SSSA[Z]'));
console.log(resultTime.toISOString());
<script src="https://momentjs.com/downloads/moment.js"></script>

请参阅this 以了解如何管理 UTC 偏移量。

【讨论】:

  • moment(date).utc().startOf('day') 不是一个好主意,因为它可能会根据代码运行时间和主机偏移量将日期偏移 ±1 天。对我来说,它目前正在返回“2020-12-09T22:00:00.000Z”,这不是 OP 想要的。 VLAZ 评论中的答案效率更高且不易出错。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-16
  • 1970-01-01
  • 2022-07-27
相关资源
最近更新 更多