My Question is how do I calculate how much hours and minutes will pass to reach specific time. I mean if we have time: 15:32, and I want to calculate how much hours is needed to 05:32 (at night), in this case should be 14 hours and 32mins.

As I don't really have that much of a knowledge and experience I haven't tried anything because I don't really know where to start.

const curDate = new Date().toLocaleTimeString();
console.log(curDate);

//I only know how to get the current date to string. But what next?

1 Answers

0
nick zoum On Best Solutions

To get the hours and minutes until a certain time of the day is reached then you should do the following steps:

  1. Create a date object with the current date
  2. Create a date object with the hour and minutes you are searching for
  3. Get the difference between the hours of the two (if it's smaller than 0 then that means that time has passed for the day so look for the next day)
  4. Get the difference between the minutes of the two (if it's smaller than 0 then that minutes that the minutes have passed, so check for the next hour)

Since you are subtracting a date from another date you don't need to do any conversions (Local => UTC)

const curDate = new Date(); // Step 1
const night = new Date(0, 0, 0, 5, 32); // Step 2
var hours = night.getHours() - curDate.getHours(); // Step 3a
if (hours < 0) hours += 24; // Step 3b
var minutes = night.getMinutes() - curDate.getMinutes(); // Step 4a
if (minutes < 0) { // Step 4b
  hours -= 1;
  minutes += 60;
}
console.log(["Hours: ", hours, ", Minutes: ", minutes].join(""));

Here is an example to help you understand step 4:

  • 08:54 - 07:56
  • 08 - 07 hours, 54 - 56 minutes
  • 1 hour, -2 minutes
  • 1 hour -1 hour => -2 minutes + 60 minutes
  • 0 hours, 58 minutes