Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get start and end of day in Javascript?

Tags:

javascript

How to get start ( 00:00:00 ) and end ( 23:59:59 ) of today in timestamp ( GMT )? Computer use a local time.

like image 401
Bdfy Avatar asked Dec 26 '11 14:12

Bdfy


People also ask

What is now () in JavaScript?

now() method is used to return the number of milliseconds elapsed since January 1, 1970, 00:00:00 UTC. Since now() is a static method of Date, it will always be used as Date.

How do I get the day before JavaScript?

How do you get yesterdays' date using JavaScript? We use the setDate() method on yesterday , passing as parameter the current day minus one. Even if it's day 1 of the month, JavaScript is logical enough and it will point to the last day of the previous month.

What is setTime in JavaScript?

setTime() The setTime() method sets the Date object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC.


2 Answers

var start = new Date(); start.setUTCHours(0,0,0,0);  var end = new Date(); end.setUTCHours(23,59,59,999);  alert( start.toUTCString() + ':' + end.toUTCString() ); 

If you need to get the UTC time from those, you can use UTC().

like image 183
tvanfosson Avatar answered Oct 12 '22 08:10

tvanfosson


With dayjs library, use startOf and endOf methods as follows:

Local GMT:

const start = dayjs().startOf('day'); // set to 12:00 am today const end = dayjs().endOf('day'); // set to 23:59 pm today 

For UTC:

const utc = require('dayjs/plugin/utc'); dayjs.extend(utc);  const start = dayjs.utc().startOf('day');  const end = dayjs.utc().endOf('day');  

Using the (deprecated) momentjs library, this can be achieved with the startOf() and endOf() methods on the moment's current date object, passing the string 'day' as arguments:

Local GMT:

var start = moment().startOf('day'); // set to 12:00 am today var end = moment().endOf('day'); // set to 23:59 pm today 

For UTC:

var start = moment.utc().startOf('day');  var end = moment.utc().endOf('day');  
like image 39
chridam Avatar answered Oct 12 '22 09:10

chridam