WoJ
WoJ

Reputation: 29987

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

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.

Upvotes: 118

Views: 186825

Answers (2)

Hasan Tezcan
Hasan Tezcan

Reputation: 1232

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(),
});

Upvotes: -1

David784
David784

Reputation: 7464

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>

Upvotes: 216

Related Questions