Javascript 如何用时刻获得一天的开始和结束?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49909213/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:31:05  来源:igfitidea点击:

How to get the beginning and end of the day with moment?

javascriptmomentjs

提问by WoJ

I would like to get the beginning and end of the current day (and accessorily of tomorrow by .add(1, 'day')) using moment.

我想.add(1, 'day')使用moment.

What I am getting now is

我现在得到的是

now = moment()
console.log('now ' + now.toISOString())
console.log('start ' + now.startOf('day').toISOString())
console.log('end ' + now.endOf('day').toISOString())
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.js"></script>

This outputs right now

这现在输出

now 2018-04-18T21:20:02.010Z
start 2018-04-17T23:00:00.000Z
end 2018-04-18T22:59:59.999Z

Since the times are shifted by an hour, I believe that this is something related to timezones, though I fail to understand how this can be relevant: no matter the time zone, the day in that timezone begins right after midnight today and ends right before midnight today.

由于时间偏移了一个小时,我认为这与时区有关,尽管我无法理解这有什么关系:无论时区如何,该时区中的一天都在今天午夜之后开始并在此之前结束今天午夜。

回答by David784

It is giving you midnight local time, but you're printing it out in zulu time. Try using toStringinstead, it will print the time out in local time.

它给你当地时间午夜,但你在祖鲁时间打印出来。尝试使用toString,它会在本地时间打印超时。

now = moment()
console.log('now ' + now.toString())
console.log('start ' + now.startOf('day').toString())
console.log('end ' + now.endOf('day').toString())
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.js"></script>