Milliseconds Seconds since 1970

I have a Xojo app which is communicating with a HTMLViewer, and the two need to agree precisely on the time.

In JavaScript, if you do this:
var now = Date.now() / 1000.0; // convert milliseconds to seconds
you will get the number of seconds since 1970 in GMT-0, accurate to the millisecond.

However in Xojo, if you do this:

dim d as new Date
d.GMTOffset = 0
dim now as double  = d.TotalSeconds // uses 1904 epoch
now = now - 2082844800           // convert 1970 to 1904 see https://www.epochconverter.com/mac     
return now

I get the same answer, however in Xojo the seconds value is always an integer (e.g. there are no milliseconds).

Is there a way in Xojo to get the same number accurate to a millisecond?

Have you tried DateTime?

I think that handles nanoseconds but because it uses double I don’t know if you are going to get the same exact milliseconds.

I’m using Xojo 2019, so there’s no DateTime class.

Here’s a way to do it using MBS Plugin:

Public Function SecondsSince1970() as double
  // on macOS, Date.TotalSeconds always returns an integer # of seconds, but we need millisecond accuracy
  // use CFAbsoluteTime instead
  #if TargetMacOS
    dim cfa as new CFAbsoluteTimeMBS
    dim now as double = cfa.Value
    now = now + 978307200.0  // see https://opensource.apple.com/source/CF/CF-368/NumberDate.subproj/CFDate.c.auto.html
    return now
  #else
    dim d as new Date
    d.GMTOffset = 0
    dim now as double  = d.TotalSeconds // uses 1904 epoch
    now = now - 2082844800.0           // convert 1970 to 1904 see https://www.epochconverter.com/mac     
    return now
  #endif
  
  
  
End Function
1 Like

The SecondsFrom1970 property in DateTime is a Double and it looks like it gives you microseconds.

To which function do you refer?

I had a prior function there which was broken, I think you caught me in mid-edit. The function posted now seems to work.