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

JavascriptMomentjs

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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>

Solution 2 - Javascript

If you want to start with Monday you have to use this one moment().startOf('isoWeek');

console.log({
  from_date: moment().startOf('isoWeek').toString(),
  today: moment().toString(),
  to_date: moment().endOf('isoWeek').toString(),
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWoJView Question on Stackoverflow
Solution 1 - JavascriptDavid784View Answer on Stackoverflow
Solution 2 - JavascriptHasan TezcanView Answer on Stackoverflow