javascript - 如何在没有时区转换的情况下即时输出日期/时间

标签 javascript timestamp momentjs

我有一个来自后端的时间戳,我想在每个 console.log() 中使用 momentjs 显示它,而不进行时移,并且完全独立于我的浏览器时区。我在 stackoverflow 上读了很多帖子,但没有任何效果。我的所有输出都包含一些时区。

let timestamp = "2019-11-19T07:05:00+01:00";
console.log(moment(timestamp).toISOString(true));
console.log(moment.utc(timestamp).format());
console.log(moment.utc(timestamp).toISOString(true)); 
console.log(moment.parseZone(timestamp).format());
console.log(moment.parseZone(timestamp).local().format());
console.log(moment.parseZone(timestamp).utc().format());
console.log(moment(timestamp).utcOffset(timestamp).toISOString(true));
console.log(moment.tz(timestamp, 'Europe/Berlin').toISOString(true));
console.log(moment.tz(timestamp, 'Europe/Berlin').format());
console.log(moment.tz(timestamp, 'Europe/Berlin').unix());
console.log(moment.parseZone(timestamp).format('MM/DD/YYYY HH:mm:ss'));
console.log(moment(timestamp).utcOffset("+0100").format('YYYY-MM-DD hh:mm:ss'));

预期输出: 2019-11-19T07:05:00Z 时间戳的时区为: Europe/Berlin 我的浏览器时区已切换为不同的时区。 我不明白为什么这个简单的问题没有简单的解决方案。 :)

最佳答案

为了满足您所描述的要求(在更改偏移量的同时保持本地时间),您可以执行以下操作:

var result = moment.parseZone("2019-11-19T07:05:00+01:00").utcOffset(0, true).format();
console.log(result); //=> "2019-11-19T07:05:00Z"
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

分步说明:

moment.parseZone("2019-11-19T07:05:00+01:00") // Parses the string, retaining the offset provided
      .utcOffset(0, true)  // sets the offset to zero while keeping the local time
      .format()            // formats the output, using Z to represent UTC

但是 - 您应该认识到这些不是同一时刻。输出时间戳比输入时间戳早一小时。这是解释in the documentation如下(强调我的):

The utcOffset function has an optional second parameter which accepts a boolean value indicating whether to keep the existing time of day.

  • Passing false (the default) will keep the same instant in Universal Time, but the local time will change.

  • Passing true will keep the same local time, but at the expense of choosing a different point in Universal Time.

因此,当您已经拥有特定时间点(UTC 格式或 UTC 偏移量(如示例输入值))时,这通常是错误的选择。

相反,您应该预期从本地时间转换为 UTC 确实会更改时间戳的日期和时间部分。您可以使用 .utcOffset(0, false).utcOffset(0) 或简单地 .utc() 来正确进行转换.

关于javascript - 如何在没有时区转换的情况下即时输出日期/时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58939414/

相关文章:

javascript - 当年份设置为20年时防止Moment js猜年份

javascript - 使用ajax发送用于文件上传的表单数据

Javascript JSON 字段在每个推送的 JSON 字符串之后都有\"

javascript - 如何使音频元素更具响应性?

正则表达式从 postgresql 中的时间戳字符串中间删除 "-"

angularjs - MomentJS 下一个 15 日

javascript - 使用JQuery获取当前文本框的ID

swift - 拖动 UITableView 或所有 TableViewCells 显示一个标签

php - 如何更改插入数据库的日期的时区?

javascript - 如何用Momentjs精确计算年龄?