I need UTC variants of the functions DateTimeToUnix
and UnixToDateTime
, so a Chinese customer is able to interact with the server in Germany. Both sides should be able to exchange Unix timestamps (in UTC, without DST) and be able to communicate through this way.
In a bugreport of HeidiSQL , users discussed that DateTimeToUnix
and UnixToDateTime
do not care about the time zone, and there I have found following code:
function DateTimeToUTC(dt: TDateTime): Int64;
var
tzi: TTimeZoneInformation;
begin
Result := DateTimeToUnix(dt);
GetTimeZoneInformation(tzi);
Result := Result + tzi.Bias * 60;
end;
MSDN explains twi.Bias
as follows:
All translations between UTC time and local time are based on the following formula:
UTC = local time + bias
The bias is the difference, in minutes, between UTC time and local time.
This sounds logical, but since I was unsure if the code above was correct, I made following program to check it:
// A date in summer time (DST)
Memo1.Lines.add('1401494400'); // 31 May 2014 00:00:00 GMT according to http://www.epochconverter.com/
Memo1.Lines.add(inttostr(DateTimeToUnixUTC(StrToDate('31.05.2014'))));
// A date in winter time
Memo1.Lines.add('567302400'); // 24 Dec 1987 00:00:00 GMT according to http://www.epochconverter.com/
Memo1.Lines.add(inttostr(DateTimeToUnixUTC(StrToDate('24.12.1987'))));
The output in Germany (GMT+1+DST) is currently:
1401494400
1401490800
567302400
567298800
I expected the output being:
1401494400
1401494400
567302400
567302400
What am I doing wrong?
PS: For this project I am bound to Delphi 6.
Unix timestamps are always based on UTC (otherwise known as GMT). It is illogical to think of a Unix timestamp as being in any particular time zone. Unix timestamps do not account for leap seconds.
By convention, meteorologists use just one time zone: Universal Time, Coordinated (UTC). They also use the twenty four hour clock (where 0000 = midnight UTC). The date/time stamp on each forecast image represents the time at which the forecast is valid, measured in UTC.
DateTime to Unix timestamp in UTC Timezone In the time module, the timegm function returns a Unix timestamp. The timetuple() function of the datetime class returns the datetime's properties as a named tuple. To obtain the Unix timestamp, use print(UTC).
Notice that UNIX Epoch is UTC so it identifies without errors a specific moment in time. Never ask about the timezone of a UNIX epoch timestamp, it is UTC by definition.
You have already found DateTimeToUnix
and UnixToDateTime
. So that part of the conversion is taken care of.
All you need to do now is convert between local and UTC time. You can do that using DateUtils.TTimeZone
class. Specifically DateUtils.TTimeZone.ToUniversalTime
and DateUtils.TTimeZone.ToLocalTime
.
These four functions give you all that you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With