
In this article, we’ll learn how to use the UTC date-time in a React Native application using JavaScript. This is to handle timezone differences between the client and the server. Imagine that you have a global application that has users in both Europe and Asia. And a user creates a calendar event in Europe. The users in Asia now should be able to see appropriate event times based on their time zone.
How to do it?
Let’s start with how we can convert the date timezone between local time and the UTC date-time on Android and iOS.
Note: When you are testing the Date conversion using a debugger, it uses the Browser’s date. And not the device’s date. So integrate Date without debugging mode.
1. Getting Current UTCTime String:
2. Converting device local time to UTC time string:
If the date is a string, and in the format "2021–10–22" (yyyy-MM-dd), convert it to a standard time string. For example, to "2020–10–21T19:00:00.000Z"
Then use the following method to convert this standard date string to UTC date-time string:
3. Converting UTC date-time string to device’s local time:
Make sure your UTC date-time string is in the standard format, for example "2021–10–22T05:00:00.000Z"
Then use the following method to convert this date string into the device’s local date:
Summary:
Sometimes the Date object is hard to work with. For example, some libraries do not work as expected. Thus, using these functions will be a lifesaver. They definitely helped me with a recent project. And I thought about sharing my experience with you.