Hirdesh Singh
Hirdesh Singh

Reputation: 23

How do you get the Unix timestamp for the end of today in Javascript?

I want to get the end Unix timestamp of today.

Get start timestamp of today using this but I want end timestamp of today

var now = new Date();
var startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var timestamp = startOfDay / 1000;

Upvotes: 1

Views: 2063

Answers (3)

S. Hesam
S. Hesam

Reputation: 6773

At First, get today timestamp:

var now = new Date();

Then get the start of tomorrow:

var startOfTomorrow = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDay() + 1);

Now you have end of today:

var timestampOfEndOfDay = (startOfTomorrow - 1); 

See the result:

console.log("End of the Day", new Date(timestampOfEndOfDay) );

Upvotes: 0

Slai
Slai

Reputation: 22906

864e5 is the number of milliseconds in a day (24 * 60 * 60 * 1000), and now % 864e5 is the time part of the date in milliseconds :

var now = new Date
var startOfDay = new Date(now - now % 864e5)
var endOfDay   = new Date(now - now % 864e5 + 864e5 - 1)

console.log(now)
console.log(startOfDay)
console.log(endOfDay)

Upvotes: 1

Alexandr Tovmach
Alexandr Tovmach

Reputation: 3179

  1. You can use .valueOf() method, to get milliseconds timestamp from date, instead of date / 1000
  2. To get end of the day, just take next day date and reduce for 1 millisecond

var now = new Date();
var startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
// take next day date and reduce for one millisecond
var endOfDay = new Date(new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1) - 1);

console.log({
  startOfDay,
  endOfDay,
  startOfDayTimestamp: startOfDay.valueOf(),
  endOfDayTimestamp: endOfDay.valueOf()
})

Upvotes: 0

Related Questions