【发布时间】:2018-11-17 00:08:05
【问题描述】:
我想计算与 UTC 时间的相对时间。我的当地时间是 +2。
我尝试了很多组合... 例如
const endDate = new Date("08 Jun 2018") // tomorrow's date, I am expecting the time is 00:00:00
const utcDateTime = new Date(moment.utc().format());
const format = 'YYYY-MM-DD HH:mm:ss';
console.log(moment(endDate).fromNow()) // example for Poland(+2) it is 12, but I want to UTC(0), so it is should be 14
console.log(moment(endDate).from(utcDateTime)) // the same
console.log(moment(endDate.toUTCString()).from(utcDateTime)) // the same
console.log(moment(moment(endDate).utc().format(format), format).fromNow()) // I do not why, but it is 10, not 14
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js
"></script>
每次我得到相对时间,这对于我的当地时间是正确的。 UTC 应该大 2 小时。
我不知道该怎么做...
有人可以帮我吗?
谢谢!
编辑
根据@31piy 的建议,我尝试过类似的方法。
const endDate = new Date("08 Jun 2018") // tomorrow's date, I am expecting the time is 00:00:00
const format = 'YYYY-MM-DD HH:mm:ss';
console.log(moment(endDate).from(moment(moment.utc().format(format), format)))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js
"></script>
它对我有用,但是......我怎样才能更清楚地做到这一点?有可能吗?
EDIT2
这是我的错...我将一个位于 UTC 时区的日期(“2018 年 6 月 8 日”)传递给 Date 构造函数,但我没有指定它是 UTC - 所以实际上 endDate 应该是相等的到"08 June 2018 02:00:00",而不是"08 Jun 2018 00:00:00"。我解决了这个问题,非常清楚 moment(endDate).fromNow(true) 正在为我工作。
感谢您帮助我!
【问题讨论】:
-
这个话题的答案对我没有帮助......事实上,我认为问题在于,我不想改变“endDate”,但我想改变“now”的值。它应该是 UTC(对我来说是本地 2),但它是从本地计算相对时间。但是,从 UTC 日期开始,它也无法正常工作,我不知道该怎么做。
标签: javascript timezone momentjs utc