0

I've been chasing my tail with JavaScript Date and thought I ask here to see if anyone could help.

From a Unix epoch value (millisonds), I'd like to extract the date components (day, month, ..., hours, min) to display them in JavaScript.

For instance this Epoch time 1674434520 (23 January 2023 00:42:00) should give

day=23
month=1 (or 0, when 0-based, I don't mind)
year=2023
hour=0
minute=42

The problem is that in order to convert all the datetime components, I need to convert the Unix epoch number into a JavaScript date (new Date(epoch)) at which time, it'll assume my browser's local time zone settings (which is not GMT) [1].

I'd like to be able to extract the datetime components regardless of the local browser settings.

Any idea how this can be achieved without external libraries? If possible, I would like to avoid unnecessary parsing/formatting ( Intl.DateTimeFormat approach) or shifting of the date (to avoid potential leap year/daylight saving issues).


[1] when displaying the dates using devtools or accessing getHours(), etc (clarified what I meant by "assume" based on @Bergi's comment).

orange
  • 7,755
  • 14
  • 75
  • 139
  • 2
    See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl – Ronnie Royston Jan 24 '23 at 00:10
  • I did have a look at the `Intl.DateTimeFormat`, but from what I can tell, it serves the purpose of formatting dates. I could apply a formatter for each datetime component and parse it back to an integer value, but I was hoping there's a more direct way of achieving this. – orange Jan 24 '23 at 00:20
  • 1
    "*at which time, it'll assume my browser's local time zone settings*" - no. That is only happening when you display the date object anywhere (including devtools), using `.toString()`. Just use the `getUTC…()` methods instead. – Bergi Jan 24 '23 at 00:32
  • 1
    @RonnieRoyston Not necessary. – Bergi Jan 24 '23 at 00:32
  • That's the answer I was looking for @Bergi. I was using `getHours`, etc, not knowing that there are special `getUTC...` functions. Thanks so much! – orange Jan 24 '23 at 00:35

0 Answers0