3

I have user's timezone, let say

timeZone: 'America/New_York'

I want to perform some tasks at midnight according to the user's timezone. How can I check if the midnight has arrived in this timezone?

Saad8113
  • 143
  • 2
  • 7
  • Does this answer your question? => https://stackoverflow.com/questions/6525538/convert-utc-date-time-to-local-date-time – Silvan Bregy Feb 24 '22 at 08:24
  • Does this answer your question? [Convert UTC date time to local date time](https://stackoverflow.com/questions/6525538/convert-utc-date-time-to-local-date-time) – Silvan Bregy Feb 24 '22 at 08:24

1 Answers1

3

Last midnight in a specific timezone:

new Date(new Date().toLocaleDateString('en-US', { timeZone: 'America/New_York', timeZoneName: 'short' } ))

Database friendly UTC time of last midnight in a specific timezone

new Date(new Date().toLocaleDateString('en-US', { timeZone: 'America/New_York', timeZoneName: 'short' } )).toISOString()

Note: understand 'last midnight' as today-in-zone midnight

Explanation:

  • new Date() is current time (whatever the zone - time object)

  • .toLocaleDateString('en-US', { timeZone: 'America/New_York', timeZoneName: 'short' } ) displays the current date (no time, so midnight) in the specified zone (string of time with zone ref)

  • new Date(<above midnight time in zone>) parse the midnight time in zone and display corresponding current timezone time (time object)

  • .toISOString() display above at UTC reference (ISO datetime string)

jobwat
  • 8,527
  • 4
  • 31
  • 30