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

纵饮孤独 提交于 2020-12-02 00:08:12

问题


I would like to get the beginning and end of the current day (and accessorily of tomorrow by .add(1, 'day')) using 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.


回答1:


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

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>


来源:https://stackoverflow.com/questions/49909213/how-to-get-the-beginning-and-end-of-the-day-with-moment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!