Define the timezone dynamically depending on other field value


#1

Hi there, it’s me again. This time I have a particular problem that I’m sure you can help me with. I have a table that contains some records with date and time information stored in UTC, in a field that we will call timestamp_utc and also an additional field that stores a specific time zone name, which we will call time_zone_to_convert.

Now, what I am needing is to convert the date and time stored in the timestamp_utc field to the time zone that is defined in the time_zone_to_convert field.

I was reading the chartafctor documentation about time zones, and I know that you can define time zones for all fields or for some specific fields. But how can I convert the field to different time zones?

Thank in advance.


#2

Hi @dev.tree, in this case you can do that by combining two features that ChartFactor provides, the Derived Fields and the ChartFactor Object dependencies. Take a look at the following metadata definition:

let timestamp_tz_converted = {
    'name': 'timestamp_tz_converted',
    'label': 'Time Zone Converted',
    'type': 'TIME',
    'timestampGranularity': 'MONTH',
    // Setting the dependency fields
    'dependencies': ['timestamp_utc', 'time_zone_to_convert'],
    'function': function (utcDate, tzToConvert) {
      // Getting the moment lib from chartfactor dependencies
      const moment = cf.getDependency('moment');
     // Converting the utc stored datetime to the custom TimeZone
      return moment.utc(utcDate).tz(tzToConvert).format();
    }
};

let _META_ = {
    "datasource_name": {
      "fields": {
        "timestamp_tz_converted": timestamp_tz_converted
      }
    }
}

For more info about how the timezones works in the momentjs library visit this url.

Let me know if you have additional questions. Best regards.


#3

That is great @juan.dominguez!, excellent solution. Thanks.