468

How to get start ( 00:00:00 ) and end ( 23:59:59 ) of today in timestamp ( GMT )?

Computer uses local time.

1
  • To get local time use var end = new Date; end.setHours(23,59,59,999); console.log(end); Approved answer gives you wrong timestamp Commented Mar 7, 2024 at 11:10

15 Answers 15

844

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

Sign up to request clarification or add additional context in comments.

6 Comments

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
@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.
I would also recommend using setUTCHours instead of setHours to get Universal time
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.
Please read @sidonaldson's extremely important comment. Using setHours is dangerous as it sets the local hours, instead of UTC hours.
|
266

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

8 Comments

And we should use .toDate() in the end to get the date. var end = moment().endOf('day').toDate();
add .unix() at the end to get unix timestamp in seconds :) like this: moment().startOf('day').unix()
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.
@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().
MomentJs is now deprecated - might consider providing an option in date.fns
|
24

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,
})

Comments

15

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)

Comments

14

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.

1 Comment

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!
12

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

2 Comments

so much more helpful!
it seems dayjs also support dayjs().format('YYYY-MM-DD 00:00:01')
11

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

1 Comment

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

1 Comment

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

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>

2 Comments

No support for UTC handling.
For UTC and zone support you can check github.com/marnusw/date-fns-tz
7

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.

1 Comment

This is cleaner, nice.
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')

Comments

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" }));

Comments

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

Comments

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

1 Comment

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.
1

hoping that this one might be useful:

startDate: startDate?.setHours(0, 0, 0, 0),
endDate: endDate?.setHours(23, 59, 59, 999),

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.