0

I need to get the current date in my TypeScript application. It is now 13:35 for me.

When using moment(Date.now()).toDate() I get the current date, but an hour too early than what I would expect: "2020-03-26T12:35:12.938Z"
This gives me 12:35.

When using moment(Date.now()).format("DDMMYYYY_HHmm") I get the current date with the hour I am expecting: "26032020_1335"
This gives me 13:35.

What am I missing here to get the correct date and time? To be clear, i need a Date object. Not a string.

dniHze
  • 2,162
  • 16
  • 22
JeroenR
  • 45
  • 7

1 Answers1

0

When you call moment(Date.now()).toDate(), I presume you logged that date to the console. When a date is logged to the console, it displays as an ISO 8601 date, which uses UTC time. So, it is the correct time, just in a different timezone. If you call .toString on the date you should see the correct time for your timezone.

Aplet123
  • 33,825
  • 1
  • 29
  • 55
  • I am actually displaying it on my webpage whilst debugging, but I guess it makes for the same output. You are right, using `.toString` actually displays the correct time. However when I send it to the backend trough an API-call, the date still has the wrong time. – JeroenR Mar 26 '20 at 13:04
  • If you parse the date, it'll automatically convert to the correct timezone. Remember, dates are really just a number and the timezone it displays as doesn't affect the value of that number. – Aplet123 Mar 26 '20 at 13:08
  • "*When a date is logged to the console, it displays as an ISO 8601 date, which uses UTC*" depends on the console. – RobG Mar 26 '20 at 20:16