Understanding Date & Timezone in JS & MySQL
Background
I'm developing Mindful Day which I plan to support international users with different timezone.
What affecting accuracy of datetime
- Server timezone that run NodeJS (server that runs node index.js)
- How the data is stored in database (is it containing Timezone Info e.g "YYYY-MM-DD HH:mm:ssZ" or not e.g "YYYY-MM-DD HH:mm:ss")
Findings
- print in server
new Date()
will always be in UTC no matter what the timezone of the server that runs it. It will be in format with timezone info e.g "YYYY-MM-DDTHH:mm:sssZ" - if we print in browser it will call toLocaleString() which will convert to browser / client's timezone
Supplying datestring to new Date()
- If
datestring
contains no timezone information, it will assume timezone is THE SAME AS the server that runs it (BEWARE) - If
datestring
contains timezone information (e.g 000Z), it will use the timezone info
examples:
SERVER is UTC
NO TIMEZONE
- "2024-05-21T00:43:27" -> new Date() -> will assume UTC -> Meaning UTC is 0 hours diff -> 2024-05-20T00:43:27Z (SAME with supplied)
WITH TIMEZONE
- "2024-05-21T00:43:27Z" -> new Date() -> will essume UTC (Z) -> Meaning UTC is 0 hours diff -> 2024-05-20T00:43:27Z (SAME with supplied)
SERVER IS Asia/Jakarta
NO TIMEZONE
- "2024-05-21T00:43:27" -> new Date() -> will assume Asia/Jakarta -> Meaning UTC is -7 hours before -> 2024-05-20T17:43:27Z (DIFFERENT with supplied)
WITH TIMEZONE
- "2024-05-21T00:43:27Z" -> new Date() -> will use UTC (Z) -> Meaning UTC is 0 hours diff -> 2024-05-20T00:43:27Z (SAME with supplied)
Conclusion
- Always store timezone information in date time string (e.g saving to database)
- Always use UTC in server for simplicity
- Use epoch if possible to avoid headache