I want to get Unix timestamp (time in seconds) from tomorrow.

I have tried the following with no success:

var d = new Date();
d.setDate(d.getDay() - 1);
d.setHours(0, 0, 0);
d.setMilliseconds(0);
console.log(d/1000|0)

How would I fix the above?

4 Answers

3
Dupinder Singh On Best Solutions

Just modified your code and it works fine

var d = new Date();
d.setDate(d.getDate() + 1);
d.setHours(0, 0, 0);
d.setMilliseconds(0);
console.log(d)
>> Sun Apr 21 2019 00:00:00 GMT+0530 (India Standard Time)

Hope this will work for you

1
John On

This should do it.

Copied directly from https://javascript.info/task/get-seconds-to-tomorrow

function getSecondsToTomorrow() {
  let now = new Date();

  // tomorrow date
  let tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate()+1);

  let diff = tomorrow - now; // difference in ms
  return Math.round(diff / 1000); // convert to seconds
}

console.log(getSecondsToTomorrow());

-1
IAMSTR On

you could use a third party library like moment js which makes your life alot easier

momentjs

-2
lukas22ew On

You can use a unix timestamp and add 24*60*60*1000 (same as 86400000) to the current time's timestamp. You can then pass that to new Date() like this:

  • 24 = hours
  • 60 = minutes
  • 60 = seconds
  • 1000 = converts the result to milliseconds

// Current timestamp
const now = Date.now()

// Get 24 hours from now
const next = new Date(now + (24*60*60*1000))

// Create tomorrow's date
const t = new Date(next.getFullYear(), next.getMonth(), next.getDate())

// Subtract the two and divide by 1000
console.log(Math.round((t.getTime() - now) / 1000), 'seconds until tomorrow')