Moment JS设置日期格式

时间:2019-12-13 03:47:23

标签: javascript momentjs

我有一个datetime字符串,将从中创建一个start_timeend_time变量。

预期输出: start_time应该是从现在开始的2天,从datetime字符串开始的时间,而end_time应该是从start_time开始的3小时。

代码

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script>
  const time = "2019-12-13T05:30:00+08:00"
  const date = moment(time);
  const h = date.hour();
  const m = date.minutes();
  const s = date.seconds();

  const from = moment().add(2, 'days');
  var start_time = from.clone().hour(h).minute(m).second(s);
  var end_time = start_time.clone().add(3, 'hours');

  // start_time = start_time.toISOString();
  // end_time = end_time.toISOString();

  console.log(start_time); // Expected: "2019-12-15T05:30:00+08:00"
  console.log(end_time); // Expected: "2019-12-15T08:30:00+08:00"
</script>

预期结果:

开始时间:“ 2019-12-15T05:30:00 + 08:00”

结束时间:“ 2019-12-15T08:30:00 + 08:00”

当前结果:

开始时间:“ 2019-12-14T21:30:00.604Z”

结束时间:“ 2019-12-15T00:30:00.604Z”

在这种情况下,如何正确格式化日期以达到预期效果的任何想法?

2 个答案:

答案 0 :(得分:2)

这是因为您使用的是不同的时区。输入为+8时区,输出为UTC

如果添加了.format(),您将看到实际上具有正确的值。

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script>
  const time = "2019-12-13T05:30:00+08:00"
  const date = moment(time);
  const h = date.hour();
  const m = date.minutes();
  const s = date.seconds();

  const from = moment().add(2, 'days');
  var start_time = from.clone().hour(h).minute(m).second(s);
  var end_time = start_time.clone().add(3, 'hours');

  // start_time = start_time.toISOString();
  // end_time = end_time.toISOString();

  // added .format()
  console.log(start_time.format()); // Expected: "2019-12-15T05:30:00+08:00"
  console.log(end_time.format()); // Expected: "2019-12-15T08:30:00+08:00"
</script>

答案 1 :(得分:1)

尝试这样:

var start_time:moment().add(2,'days');
var end_time:moment().add(2,'days').add(3,'hours')