Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 577
WoJ Avatar asked Apr 18 '18 21:04

WoJ


People also ask

How do you find the beginning of the month with a moment?

Use the Moment.We call moment to create a Moment object with the current date and time. Then we call clone to clone that object. Then we call startOf with 'month' to return the first day of the current month. And then we call format to format the date into the human-readable YYYY-MM-DD format.

How do you get the week start date and end from a moment?

to get the current date time with moment . Then we call add with 1 and 'weeks' to add 1 week to the current date and time. And then we call startOf and endOf with 'isoWeek' to get the start and end of next week respectively. isoWeek starts Monday and ends Sunday.


1 Answers

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>
like image 55
David784 Avatar answered Sep 29 '22 16:09

David784