Date weird timezone (GMT+0009)

I use ExcelJS to parse an Excel into a JavaScript Object.

Here is an excel sample : enter image description here

As you can see, I must cover multiple format for date and hour. For the date I have no problem. But when it comes to hour, cells with “12:30” and “15:00” value are returned as javascript date object. So I check if its a date or a string and I want to get the string value (10H10 and 18h30 cells are ok because they are considered as string but not the 15:00 and 12:30).

When using VSCode debug tool, I can see that I have this date :

  • 'Sat Dec 30 1899 12:39:21 GMT+0009 (Central European Standard Time)'
  • 'Sat Dec 30 1899 15:09:21 GMT+0009 (Central European Standard Time)'

What I want is a way to cast this result in a string “12:30” or “15:30”. I tried many things using moment and Date functions like .toUTCString(), .toGMTString()

Answer

I’m going to assume you have a JS Date object.

Intl.DateTimeFormat would be recommended for formatting date and/or times for users.

But since you want a specific format, it might be easier to format it yourself.

But the time isn’t in the correct time zone. You’d first have to convert it to the correct time zone. Except the correct time zone is UTC, and we can access that info about the components of the UTC representation of the date-time without doing any conversion.

[
   dt.getUTCHours(),
   dt.getUTCMinutes().toString().padStart(2, '0'),
].join(":")

Leave a Reply

Your email address will not be published. Required fields are marked *