Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converto date in Java to integer and then to Delphi Time

I have a server-equipment configuration where I need to change the equip date config, using UDP. The server is written in Java and the equipment, in Delphi.

So, the flow of the data is this:

Java server (Java date) -> UDP (integer date) -> Delphi equipment (Delphi date)

The problem is that when I pass the date as an integer, java calculates miliseconds from 1970, and Delphi, seconds. I pass then the date as following: today.getTime() / 1000, but the equipment understands this as a 2008 date, when we're on 2012.

I can change the Java code, but the equipment is 3rd party and I don't have access to it's source code.

There's difference between Java and Delphi date parsing that allow this discrepancy?

EDIT: Thanks to MДΓΓ БДLL I noticed I was multiplying by 1000 instead of dividing by it, I now have a better date, but still wrong (was somewhen in 2033, now it's in 2008).

like image 946
Rodrigo Castro Avatar asked Jan 03 '12 18:01

Rodrigo Castro


1 Answers

Delphi's DateUtils unit has UnixToDateTime() and DateTimeToUnix() functions for converting between TDateTime and Unix timestamps, which are expressed as seconds from the Unix epoch (Jan 1 1970 00:00:00 GMT):

// 1325606144 = Jan 3 2012 3:55:44 PM GMT

uses
  DateUtils;

var
  DT: TDateTime;
  Unix: Int64;
begin
  DT := UnixToDateTime(1325606144);
  // returns Jan 3 2012 3:55:44 PM

  Unix := DateTimeToUnix(EncodeDate(2012, 1, 3) + EncodeTime(15, 55, 44, 0));
  // returns 1325606144
end;

Java's Date class, on the other hand, is based on milliseconds from the Unix epoch instead. That is easy to take into account, though:

uses
  DateUtils;

function JavaToDateTime(Value: Int64): TDateTime;
begin
  Result := UnixToDateTime(Value div 1000);
end;

function DateTimeToJava(const Value: TDateTime): Int64;
begin
  Result := DateTimeToUnix(Value) * 1000;
end;

Alternatively:

uses
  SysUtils, DateUtils;

// UnixDateDelta is defined in SysUtils...

function JavaToDateTime(Value: Int64): TDateTime;
begin
  Result := IncMilliSecond(UnixDateDelta, Value);
 end;

function DateTimeToJava(const Value: TDateTime): Int64;
begin
  Result := MilliSecondsBetween(UnixDateDelta, Value);
  if Value < UnixDateDelta then
    Result := -Result;
end;

Either way:

// 1325606144000 = Jan 3 2012 3:55:44 PM GMT

var
  DT: TDateTime;
  Java: Int64;
begin
  DT := JavaToDateTime(1325606144000);
  // returns Jan 3 2012 3:55:44 PM

  Java := DateTimeToJava(EncodeDate(2012, 1, 3) + EncodeTime(15, 55, 44, 0));
  // returns 1325606144000
end;
like image 130
Remy Lebeau Avatar answered Sep 20 '22 00:09

Remy Lebeau