Dynamics 365 Business Central: How to get timezone offset in AL

Dynamics 365 Business Central

Hi, Readers.
Today I would like to briefly talk about how to get timezone offset in AL.
Time-related data is a common requirement for many applications. And a timezone offset is the difference in hours between a particular time zone and UTC. For example, (UTC+09:00) Osaka, Sapporo, Tokyo: Japan time zone, timezone offset is +9 hours.

(UTC-10:00) Hawaii: Hawaii time zone, timezone offset is -10 hours.

This may be useful when your system integrates with an external system and the time zones are different, or if your users are in different time zones and need to deal with differences between time zones. So how to do it?
It’s not very difficult, let’s see more details.
In codeunit 10 “Type Helper”, we can find a standard method, GetUserTimezoneOffset.

To facilitate calculation, the Duration Data Type is used.
Duration Data Type: Represents the difference between two DateTimes. This value can be negative. More details: Dynamics 365 Business Central: Working with Duration Data Type

Let’s look at a simple example.

(UTC+09:00) Osaka, Sapporo, Tokyo:

(UTC-10:00) Hawaii:

Source code:

pageextension 50115 ZYCustomerListExt extends "Customer List"
{
    trigger OnOpenPage()
    var
        TypeHelper: Codeunit "Type Helper";
        TimezoneOffset: Duration;
    begin
        if not TypeHelper.GetUserTimezoneOffset(TimezoneOffset) then
            TimezoneOffset := 0;
        Message(Format(TimezoneOffset));
    end;
}

Test video:

Since we get the Duration Data Type, it’s easy to calculate. For example, we can use the current datetime to calculate UTC via timezon offset.

Source code:

pageextension 50115 ZYCustomerListExt extends "Customer List"
{
    trigger OnOpenPage()
    var
        TypeHelper: Codeunit "Type Helper";
        LocalDateTime: DateTime;
        UTC: DateTime;
        TimezoneOffset: Duration;
        Msg: Label 'UTC is %1.\Timezone Offset: %2\Local Datetime is %3';
    begin
        LocalDateTime := CurrentDateTime;
        if not TypeHelper.GetUserTimezoneOffset(TimezoneOffset) then
            TimezoneOffset := 0;
        UTC := LocalDateTime - TimezoneOffset;
        Message(Msg, UTC, TimezoneOffset, LocalDateTime);
    end;
}

Great, give it a try!!!😁

PS: Dynamics 365 Business Central: How to quickly get Coordinated Universal Time (UTC Time)

END

Hope this will help.

Thanks for reading.

ZHU

コメント

Copied title and URL