Search code examples
javascriptreactjsmeteormomentjsmoment-timezone

Date Picker get Date in given timezone instead of local time


In my react application, when i creating a new date object for date-picker using moment-timezone package(with different timezone), the time is automatically converting to the local system time + the chosen timezone time. Is there any way to create a new date object with set a timezone on client side? i am using moment-timezone for globalization and Meteor Js for back-end


Solution

  • If I understand correctly, your issue is that you want to provide a Date Picker UI that automatically generates a Date object from the selected date and user time zone setting (retrieved from your database), but what you get is a date in user's local time (hence may already have some timezone offset) + the user time zone offset setting.

    You have mainly 3 possible solutions:

    1. Have the Date Picker UI always provide a date in UTC (typically at midnight UTC), then add your user's timezone offset setting.
    2. Have the Date Picker UI take your user's timezone setting as a configuration, so that when it automatically generates a Date, it uses that timezone offset configuration.
    3. Have the Date Picker UI provide a Date in the browser local time, then shift it to UTC, then add your user's timezone offset setting.

    Option 1 DatePicker in UTC: I have not seen any library that provides such option, but it does not sound too weird, so you may find one that does. Or you may fiddle with the component code... which is probably overkill compared to option 3.

    Option 2 DatePicker with timezone configuration: from your comment, this sounds like what you expect. Unfortunately, I have not seen any library that offers such feature either. As this sounds even more specific than option 1, it is unlikely you can find such a library.

    Option 3 local time shift to UTC then add user timezone: this is the standard practice to achieve the objective of generating a Date in a given timezone, starting from a Date in local time, due to all DatePicker UI working just with local time to simplify things. As to shift local time to UTC, you should have plenty questions and answers on SO already.

    In case you have to provide an initial value to your Date Picker UI (typically a previous value from database), then make sure to perform the reverse operation, i.e. subtract your user's timezone offset setting to get a date in UTC, then shift to browser locale time. I have seen applications that neglect this part and have incorrect date when the local time has a negative offset to UTC.