1

I want to find out if the current UTC time is at least 12 hours bigger than the given UTC time. The given UTC time always consists of UTCyear, UTCmonth, UTCdate, UTChour and UTCminute.

I have tried it with the code provided in the answer from the user Titulum, but it's not always working. For example, the code is not working in this case:

function isOlderThan12Hours(dateToCheck)
{
    return Date.now() - dateToCheck > 43200;
}

const year = 2020;
const month = 3;  // April
const date = 17;
const hour = 11;
const minute = 39;

const valuesAsDate = new Date(`${year}-${month+1}-${date}T${hour}:${minute}:00.000Z`);

In this case, valuesAsDate is "Invalid Date".

How can I find out if the current UTC time is at least 12 hours bigger than the given UTC time?

Tobey60
  • 147
  • 1
  • 5
  • Convert them to second and check if one is bigger from another at least 43200 s which is 12 hours – Mortimer Apr 03 '20 at 08:14
  • Does this answer your question? [How to get the hours difference between two date objects?](https://stackoverflow.com/questions/19225414/how-to-get-the-hours-difference-between-two-date-objects) – Pac0 Apr 03 '20 at 08:14
  • note that the fact that they are "UTC" is irrelevant here. – Pac0 Apr 03 '20 at 08:15
  • 1
    UTC is relevant in that you need to construct the past date with [Date.UTC()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC) not new Date(). – Rup Apr 03 '20 at 08:19

1 Answers1

0

function isOlderThan12Hours(dateToCheck) {
  return Date.now() - dateToCheck > 43200;
}

const year = 2019;
const month = 11; // December
const date = 31;
const hour = 16;
const minute = 40;

const valuesAsDate = new Date(year, month, date, hour, minute);

console.log(isOlderThan12Hours(valuesAsDate));
Titulum
  • 9,928
  • 11
  • 41
  • 79
  • What do you mean @Teemu? The code is just an example because that is how the OP supplied the values, but the `Date` passed to the `isOlderThan12Hours` function needs to be a valid [`Date`](https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Date) object. – Titulum Apr 03 '20 at 09:10
  • I found out that it is not working with these values: minute = 39; hour = 11; date = 17; month = 3; year = 2020; In this case, valuesAsDate is "Invalid Date". Why is this code not working with all dates? What can I change so that the code works with all future dates? – Tobey60 Apr 17 '20 at 13:03
  • Like @Teemu already said, this method has issues with the UTC date between 1 and 9. You will have to find another way to create the Date object. – Titulum Apr 20 '20 at 07:02
  • The code has been fixed, please remove the negative downvote – Titulum Apr 20 '20 at 07:16