Javascript 如何使用 moment.js 设置 00:00:00
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34762383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set 00:00:00 using moment.js
提问by jcubic
I want to get current date but time should be 00:00:00.000
我想获取当前日期,但时间应该是 00:00:00.000
I've try this:
我试过这个:
var m = moment();
m.set({hour:0,minute:0,second:0,millisecond:0});
console.log(m.toISOString());
but I've got: 2016-01-12T23:00:00.000Z
why 23 and not 00?
但我有:2016-01-12T23:00:00.000Z
为什么是 23 而不是 00?
回答by Volodymyr Synytskyi
Moment.js stores dates it utc and can apply different timezones to it. By default it applies your local timezone. If you want to set time on utc date time you need to specify utc timezone.
Moment.js 将日期存储为 UTC 并且可以对其应用不同的时区。默认情况下,它应用您的本地时区。如果要在 utc 日期时间设置时间,则需要指定 utc 时区。
Try the following code:
试试下面的代码:
var m = moment().utcOffset(0);
m.set({hour:0,minute:0,second:0,millisecond:0})
m.toISOString()
m.format()
回答by saikumar
var time = moment().toDate(); // This will return a copy of the Date that the moment uses
time.setHours(0);
time.setMinutes(0);
time.setSeconds(0);
time.setMilliseconds(0);
回答by saikumar
You've not shown how you're creating the string 2016-01-12T23:00:00.000Z
, but I assume via .format()
.
您还没有展示如何创建 string 2016-01-12T23:00:00.000Z
,但我假设通过.format()
.
Anyway, .set()
is using your local time zone, but the Z
in the time string indicates zero time, otherwise known as UTC.
无论如何,.set()
使用的是您的本地时区,但Z
时间字符串中的 表示零时间,也称为 UTC。
https://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators
https://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators
So I assume your local timezone is 23 hours from UTC?
所以我假设您当地的时区与 UTC 相差 23 小时?
saikumar's answershowed how to load the time in as UTC, but the other option is to use a .format()
call that outputs using your local timezone, rather than UTC.
saikumar 的回答显示了如何将时间加载为 UTC,但另一种选择是使用.format()
使用本地时区而不是 UTC 输出的调用。
http://momentjs.com/docs/#/get-set/
http://momentjs.com/docs/#/displaying/format/
http://momentjs.com/docs/#/get-set/
http://momentjs.com/docs/#/displaying/format/