How to get start and end of day in Javascript?

Javascript

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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().

Solution 2 - Javascript

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'); 

Solution 3 - Javascript

Using the [luxon.js][1] library, same can be achieved using startOf and endOf methods by passing the 'day' as parameter

var DateTime = luxon.DateTime;
DateTime.local().startOf('day').toUTC().toISO(); //2017-11-16T18:30:00.000Z
DateTime.local().endOf('day').toUTC().toISO(); //2017-11-17T18:29:59.999Z
DateTime.fromISO(new Date().toISOString()).startOf('day').toUTC().toISO(); //2017-11-16T18:30:00.000Z

>remove .toUTC() if you need only the local time

and you may ask why not [moment.js][2], answer is [here][3] for that.

[1]: http://moment.github.io/luxon/ "Luxon" [2]: http://momentjs.com/ [3]: http://moment.github.io/luxon/docs/manual/why.html

Solution 4 - Javascript

FYI (merged version of Tvanfosson)

> it will return actual date => date when you are calling function

export const today = {
  iso: {
    start: () => new Date(new Date().setHours(0, 0, 0, 0)).toISOString(),
    now: () => new Date().toISOString(),
    end: () => new Date(new Date().setHours(23, 59, 59, 999)).toISOString()
  },
  local: {
  start: () => new Date(new Date(new Date().setHours(0, 0, 0, 0)).toString().split('GMT')[0] + ' UTC').toISOString(),
  now: () => new Date(new Date().toString().split('GMT')[0] + ' UTC').toISOString(),
  end: () => new Date(new Date(new Date().setHours(23, 59, 59, 999)).toString().split('GMT')[0] + ' UTC').toISOString()
  }
}

// how to use

today.local.now(); //"2018-09-07T01:48:48.000Z" BAKU +04:00
today.iso.now(); // "2018-09-06T21:49:00.304Z" * 
  • it is applicable for Instant time type on Java8 which convert your local time automatically depending on your region.(if you are planning write global app)

Solution 5 - Javascript

In MomentJs We can declare it like :

   const start = moment().format('YYYY-MM-DD 00:00:01');
   const end = moment().format('YYYY-MM-DD 23:59:59');

Solution 6 - Javascript

If you're just interested in timestamps in GMT you can also do this, which can be conveniently adapted for different intervals (hour: 1000 * 60 * 60, 12 hours: 1000 * 60 * 60 * 12, etc.)

const interval = 1000 * 60 * 60 * 24; // 24 hours in milliseconds

let startOfDay = Math.floor(Date.now() / interval) * interval;
let endOfDay = startOfDay + interval - 1; // 23:59:59:9999

Solution 7 - Javascript

I prefer to use date-fns library for date manipulating. It is really great modular and consistent tool. You can get start and end of the day this way:

var startOfDay = dateFns.startOfDay;
var endOfDay = dateFns.endOfDay;

console.log('start of day ==> ', startOfDay(new Date('2015-11-11')));
console.log('end of day ==> ', endOfDay(new Date('2015-11-11')));

<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.29.0/date_fns.min.js"></script>

Solution 8 - Javascript

We can use moment for this.

// for day start time
moment(moment().startOf('day')).format('HH:mm')

// for day end time
moment(moment().endOf('day')).format('HH:mm')

Solution 9 - Javascript

As you are interested in the UTC start/end of day, you can also use to modulo operator:

const now = new Date().getTime();
let startOfDay = now - (now % 86400000);
let endDate = startOfDay + 86400000;

where 86400 is the number of seconds of one day and the resulting variables are the Epoch in milliseconds.

If you prefer Date Objects:

const now = new Date().getTime();
let startOfDay = new Date(now - (now % 86400000));
let endDate = new Date(now - (now % 86400000) + 86400000);

Solution 10 - Javascript

It might be a little tricky, but you can make use of Intl.DateTimeFormat.

The snippet bellow can help you convert any date with any timezone to its begining/end time.

const beginingOfDay = (options = {}) => {
  const { date = new Date(), timeZone } = options;
  const parts = Intl.DateTimeFormat("en-US", {
    timeZone,
    hourCycle: "h23",
    hour: "numeric",
    minute: "numeric",
    second: "numeric",
  }).formatToParts(date);
  const hour = parseInt(parts.find((i) => i.type === "hour").value);
  const minute = parseInt(parts.find((i) => i.type === "minute").value);
  const second = parseInt(parts.find((i) => i.type === "second").value);
  return new Date(
    1000 *
      Math.floor(
        (date - hour * 3600000 - minute * 60000 - second * 1000) / 1000
      )
  );
};

const endOfDay = (...args) =>
  new Date(beginingOfDay(...args).getTime() + 86399999);

const beginingOfYear = () => {};

console.log(beginingOfDay({ timeZone: "GMT" }));
console.log(endOfDay({ timeZone: "GMT" }));
console.log(beginingOfDay({ timeZone: "Asia/Tokyo" }));
console.log(endOfDay({ timeZone: "Asia/Tokyo" }));

Solution 11 - Javascript

// get current time for UTC timezone
const d = new Date();
const year = d.getUTCFullYear();
const month = d.getUTCMonth();
const day = d.getUTCDate();
// set time to begin day UTC
const startTime = Date.UTC(year, month, day, 0, 0, 0, 0);
//set time to end day UTC
const endTime = Date.UTC(year, month, day, 23, 59, 0, 0);

Solution 12 - Javascript

One liner - considering local timezone and without libraries

const todayStart = new Date(new Date().setHours(0, 0, 0, 0))
const todayEnd = new Date(new Date().setHours(23, 59, 59, 999))

const tomorrowStart = new Date(new Date(new Date().setHours(0, 0, 0, 0)).setDate(new Date().getDate() + 1))
const tomorrowEnd = new Date(new Date(new Date().setHours(23, 59, 59, 999)).setDate(new Date().getDate() + 1))

const monthStart = new Date(new Date(new Date().getFullYear(), new Date().getMonth(), 1).setHours(0, 0, 0, 0))
const monthEnd = new Date(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0).setHours(23, 59, 59, 999))

const nextMonthStart = new Date(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 1).setHours(0, 0, 0, 0))
const nextMonthEnd = new Date(new Date(new Date().getFullYear(), new Date().getMonth() + 2, 0).setHours(23, 59, 59, 999))

console.log({
  todayStart,
  todayEnd,
  tomorrowStart,
  tomorrowEnd,
  monthStart,
  monthEnd,
  nextMonthStart,
  nextMonthEnd,
})

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
QuestionBdfyView Question on Stackoverflow
Solution 1 - JavascripttvanfossonView Answer on Stackoverflow
Solution 2 - JavascriptchridamView Answer on Stackoverflow
Solution 3 - Javascripttk120404View Answer on Stackoverflow
Solution 4 - JavascriptMusaView Answer on Stackoverflow
Solution 5 - JavascriptAshutosh JhaView Answer on Stackoverflow
Solution 6 - JavascriptafinemonkeyView Answer on Stackoverflow
Solution 7 - JavascriptMikhail ShabrikovView Answer on Stackoverflow
Solution 8 - JavascriptSagar DavaraView Answer on Stackoverflow
Solution 9 - JavascriptromorView Answer on Stackoverflow
Solution 10 - JavascriptWeihang JianView Answer on Stackoverflow
Solution 11 - JavascriptGiangView Answer on Stackoverflow
Solution 12 - JavascriptEmanuelView Answer on Stackoverflow