390

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

Bdfy
  • 21,109
  • 53
  • 126
  • 178

12 Answers12

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

Jorge de los Santos
  • 4,525
  • 1
  • 15
  • 35
tvanfosson
  • 509,016
  • 97
  • 693
  • 791
  • 42
    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
  • 24
    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
  • sooo helpful!! great! – Darlan Dieterich Sep 13 '19 at 12:54
  • 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
255

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
  • 95,056
  • 21
  • 214
  • 219
  • 8
    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 – kris 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,855
  • 1
  • 28
  • 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! – SebastiaoRealino Jan 29 '22 at 06:51
9

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,480
  • 25
  • 23
9

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
  • 13,573
  • 9
  • 48
  • 77
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
  • 161
  • 2
  • 7
  • 2
    **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
4

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,068
  • 1
  • 22
  • 33
4

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
  • 330
  • 4
  • 10
3

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);
romor
  • 1,032
  • 13
  • 21
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
  • 6,592
  • 4
  • 42
  • 50
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
  • 1,914
  • 2
  • 22
  • 24
1

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
  • 1,656
  • 15
  • 20