0

I want to setup a setTimeout function and need to calculate the seconds for the callback. Let's say I want to execute a function at 12:00 (HH-MM) I have to calculate the timespan up to this time. If the time has already passed the next day is relevant.

I get the current date time with new Date()

I know I can calculate the timespan in seconds by using

const difference = dateTimeOne.getTime() - dateTimeTwo.getTime();
const differenceInSeconds = difference / 1000;

Is there a way creating a second date object by passing in the hours and minutes or do I have to calculate it on my own?

An example would be new Date('12:45')

3 Answers3

4

var minutes = 42;

for (var hours = 1; hours < 24; hours+=3) {
  var newAlarm = setAlarm(hours, minutes);
  out(newAlarm)
}



function out(date) {
  var now = new Date()
  
  if (date.getDate() != now.getDate()) {
    console.log('tomorrow: ' + date.getHours() + ":" + date.getMinutes())
  } else {
    console.log('today: ' + date.getHours() + ":" + date.getMinutes())
  }
}
function setAlarm(hours, minutes) {
  var now = new Date();
  var dateTarget = new Date();
  
  dateTarget.setHours(hours)
  dateTarget.setMinutes(minutes)
  dateTarget.setSeconds(0)
  dateTarget.setMilliseconds(0)
  
  if (dateTarget < now) {
    dateTarget.setDate(dateTarget.getDate()+1)
  }
  return dateTarget
}

See this Documentation on MDN

yunzen
  • 32,854
  • 11
  • 73
  • 106
  • almost, if the time has already passed I have to set the day to next day. That's why I asked if I have to do it manually –  Nov 22 '18 at 13:42
2

You can manipulate the date and then check whether it is in the past. If it is, just add another day.

const d = new Date();
d.setHours(12);
d.setMinutes(0);
d.setSeconds(0);
d.setMilliseconds(0);

if (d < new Date()) {
  d.setDate(d.getDate() + 1);
}

console.log(d);
str
  • 42,689
  • 17
  • 109
  • 127
-1

It's possible, but you need to provide the whole time string (which we can get from calling Date() and add the missing part):

const time = '12:45'
const current = new Date()
const dateTimeTwo = new Date(`${current.getFullYear()}-${current.getMonth()+1}-${current.getDate()} ${time}`)
mauleros
  • 128
  • 1
  • 7
  • thanks for your answer. I think @HerrSerker provided a cleaner solution. But as I mentioned I have to consider the next day if the time has already passed –  Nov 22 '18 at 13:48
  • Note that you are not using a [valid datetime string](https://stackoverflow.com/questions/51715259/what-are-valid-date-time-strings-in-javascript/) which will fail in certain browsers (e.g. Safari). – str Nov 22 '18 at 13:58
  • That's right, sorry. @str's solution is the correct one. – mauleros Nov 22 '18 at 14:02