How to Convert Dates into Different Time Zones in Displayr
Working with dates and times can be challenging to say the least, especially when they are in the wrong time zone or format, or you want to manipulate them in some other way. Thankfully, this is made easy in Displayr using an extremely helpful R package called lubridate.
Data sets often contain dates that a record was created, amended or a specific event took place. However, depending on how the data was collected, the date format may not be ideal. Sometimes the date may be in a different format (i.e., month–day–year instead of day/month/year). And sometimes it may be stored in UTC (Coordinated Universal Time) or the hosted server time zone instead of the local time set on your computer. Luckily there are ways to convert dates into different time zones in Displayr without a lot of hassle.
Let’s look at the following scenario. We have imported some data into Displayr but the date has been stored in UTC time. We want to change the below dates to our local Sydney time zone (AEST).
I will now show you how this is possible in Displayr using R’s lubridate package.
Using the lubridate R package in Displayr
First, we will create an R text variable in Displayr to store the new date as a string by clicking Insert > New R (Variables group) > Text Variable. Next, we will paste the code below into the R CODE box of the Object Inspector to convert the 'DateTime' variable from UTC to Sydney AEST time, then press Calculate to run it.
library(lubridate) date = force_tzs(`DateTime`, tzones = "UTC") strftime(date, format = "%Y/%m/%d %H:%M", tz = "Australia/Sydney")
In this code:
- We call the lubridate library
- As 'DateTime' is already set up as a recognizable date/time variable in Displayr, we can simply use force_tzs to append the UTC time zone to our date without the need to format it first.
- The last step is to set it back to a string using strftime in the same standard format as before (YYYY/MM/DD HH:MM) but with the specified time zone set to local Sydney time (AEST). A list of the time zone names that dates can be converted to can be found here. The advantage of using lubridate's functions instead of arbitrarily adding the current 11-hour difference between time zones is that it automatically takes into account Daylight Saving.
Set as Date/Time
Finally, to turn this from a text variable back into a date variable, we simply need to go to Properties > INPUTS in the Object Inspector and select Date/Time in the Structure drop-down.
Now we have a new date variable in our local time. It's as easy as that!
Check out more tips to make your life easier here!