430

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

Bdfy
  • 23,141
  • 55
  • 131
  • 179

14 Answers14

799

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

Engineer S. Saad
  • 378
  • 4
  • 19
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
  • 45
    I would recommend that `var end = new Date(start.getTime());` to ensure that you have same point in time - in the event you change dates between start and end initialisation - it can happen - just a good habit to get into – Martyn Davis Jan 31 '17 at 03:07
  • @MartynDavis when all is normal operation, usually about 0-2 ticks happen in between but it depends on how busy the cpu is so then it makes sense to do that if you are worried about 1 tick precision. – King Friday Apr 22 '17 at 16:16
  • 25
    I would also recommend using `setUTCHours` instead of `setHours` to get Universal time – sidonaldson Jun 12 '17 at 11:39
  • 2
    Things might have changed but for me this sets the start to UTC start for the previous day, and to UTC end for the previous day. – David J Nov 28 '18 at 19:27
  • 5
    Please read @sidonaldson's extremely important comment. Using `setHours` is dangerous as it sets the local hours, instead of UTC hours. – Michael Dec 31 '18 at 13:31
  • In 2020, you can instead use `Intl.DateTimeFormat` to handle timezones. I have posted an answer below showing how it works. Hope it helps. – Weihang Jian Oct 07 '20 at 17:29
260

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'); 
chridam
  • 100,957
  • 23
  • 236
  • 235
  • 9
    And we should use `.toDate()` in the end to get the date. `var end = moment().endOf('day').toDate();` – YaTaras Nov 28 '16 at 10:48
  • 5
    add `.unix()` at the end to get unix timestamp in seconds :) like this: `moment().startOf('day').unix()` – Lukas Liesis Jul 13 '17 at 18:58
  • 5
    moment js somehow doesn't work if I have a predefined Date object e.g. `moment(new Date()).endOf("day");`doesn't work, but `moment().endOf("day");` does work. – B. Kemmer Sep 19 '17 at 05:56
  • What about the start of day for a specified time zone? – Klas Mellbourn Dec 04 '17 at 10:17
  • how to get the start and end of a selection day? such as 01/01/2018? – Tenz Jan 06 '18 at 23:31
  • 5
    @KlasMellbourn To get the start of day for a specified timezone, you can use `moment-timezone` and do this: `moment().tz('America/Chicago').startOf('day').toDate()`. – Chad Johnson Mar 06 '18 at 23:41
  • Beware no milliseconds are added. When we send this over the wire to a .NET web api, Is there a way where this is mapped to the very last possible date for a given day? So ticks included..? – S. Robijns Jun 13 '18 at 08:00
  • 1
    MomentJs is now deprecated - might consider providing an option in date.fns – kristjan reinhold Jan 10 '22 at 10:49
15

Using the luxon.js 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, answer is here for that.

tk120404
  • 2,985
  • 1
  • 27
  • 28
  • The link explaining why not moment.js is broken. The short answer is: Moment Js recently announced that the library is now deprecated. Luxon is beautiful! – SebaReal Jan 29 '22 at 06:51
14

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)

Musa
  • 2,596
  • 26
  • 25
11

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,
})
Emanuel
  • 2,603
  • 22
  • 24
10

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');
Ashutosh Jha
  • 15,451
  • 11
  • 52
  • 85
8

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
afinemonkey
  • 171
  • 2
  • 7
  • 3
    **Important caveat:** this only works if you're wanting the time in UTC. (This is what the question asked for... but I feel I should warn anyone who came here from a Google search and didn't realize this.) – Kip Nov 19 '19 at 22:46
7

As you are interested in the UTC start/end of day, you can also use the 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);
romor
  • 1,181
  • 15
  • 22
  • The end time will be "12am" the following day, I think you want `let endDate = startOfDay + 86400000 - 1` instead to get the last millisecond of the current day. – Josh M. Jan 13 '23 at 19:23
6

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>
Mikhail Shabrikov
  • 8,453
  • 1
  • 28
  • 35
5

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')
Sagar Davara
  • 408
  • 7
  • 13
4

Based on the most rated answer, but to define the dates in just one line:

const startToday = new Date(new Date().setUTCHours(0,0,0,0));
const endToday = new Date(new Date().setUTCHours(23,59,59,999));

Explanation:

new Date().setUTCHours(0,0,0,0) // returns the epoch time number
new Date(/* epoch number */) // returns that epoch Date object 

that is why both new Date constructors are needed.

José Antonio Postigo
  • 2,674
  • 24
  • 17
1

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" }));
Weihang Jian
  • 7,826
  • 4
  • 44
  • 55
1
// 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);
Giang
  • 2,384
  • 2
  • 25
  • 26
0
// 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);
htps611
  • 1
  • 3
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center. – DSDmark Jun 02 '23 at 12:21