Saturday, August 20, 2011

PowerBuilder UTC to Local Time Zone Conversion

Received a question about how to convert UTC time to a local time zone.  Finding no PowerBuilder specific references for it, created a sample:



Local External Functions:
Function ulong GetTimeZoneInformation 
(ref TIME_ZONE_INFORMATION lpTimeZoneInformation)
Library "kernel32"
Function boolean SystemTimeToTzSpecificLocalTime
(TIME_ZONE_INFORMATION lpTimeZone, SYSTEMTIME lpUniversalTime,
ref SYSTEMTIME lpLocalTime ) Library "kernel32"

Instance variables:
Constant ulong TIME_ZONE_ID_INVALID  = 4294967295
Constant long TIME_ZONE_ID_STANDARD = 1
Constant long TIME_ZONE_ID_UNKNOWN = 0
Constant long TIME_ZONE_ID_DAYLIGHT = 2

We also need a couple of structures defined for those local external function calls:
global type systemtime from structure
integer wYear
integer wMonth
integer wDayofWeek
integer wDay
integer wHour
integer wMinute
integer wSecond
integer wMilliseconds
end type

global type time_zone_information from structure
long bias
integer standardname[31]
systemtime standarddate
long standardbias
integer daylightname[31]
systemtime daylightdate
long daylightbias
end type

Function (takes UTC datetime as argument, returns datetime converted to local time zone):
TIME_ZONE_INFORMATION tzi
SYSTEMTIME utc
SYSTEMTIME pst
ulong rc
boolean rc2

//Get's local time zone
rc = GetTimeZoneInformation(tzi)

//Convert PowerBuilder datetime to SYSTEMTIME for UTC
UTC.wYear = Year(Date(a_utc))
UTC.wMonth = Month(Date(a_utc))
UTC.wDay = Day(Date(a_utc))
UTC.wHour = Hour(Time(a_utc))
UTC.wMinute = Minute(Time(a_utc))
UTC.wSecond = Second(Time(a_utc))
UTC.wMilliseconds = 0

//Convert to local time zone
rc2 = SystemTimeToTzSpecificLocalTime(tzi, UTC, pst)

//Convert SYSTEMTIME to PowerBuilder datetime
Return DateTime ( Date ( pst.wYear, pst.wMonth, pst.wDay ),
Time ( pst.wHour, pst.wMinute, pst.wSecond ) )

1 comment:

Unknown said...

Thanks Bruce. I'm needing this right now and appreciate your cogent approach to this.
Bryan Southern