Page History: UnixTime or Epoch Time
Compare Page Revisions
Page Revision: 2017/08/02 11:41
Many computer systems store and process time as the elapsed seconds since 00h00 01/01/1970. Unixtime removes much of the hassle with dealing with dates as they are only converted back to "human readable" format when used and so will use the local date format. Any date numbers you generate can be checked against
this web tool.
The following is a function to add this facility to MMBasic. It returns the number of seconds since midnight on 1st January 1970 as an integer. UnixTime correctly takes account of leap years in its calculations but leap seconds (inserted occasionally by NIST) are ignored - this conforms with the established method of calculating UnixTime as leap seconds are arbitrary and not generally predictable. Because of this, very small errors may exist when the output is compared to astronomical clocks.
NOTE. There is dependency on the
SPLIT Function (VB work-a-like) to maintain compatibility with MM vs MMX (the respective CFunctions are not transferable). In time an additional version using the FIELD CFunction will be published. There is little sanity checking performed on the strings you provide. If you try to crash it you'll probably succeed. If the argument strings do not consist of 3 delimited values, -1 is returned to indicate an error. MMbasic uses +/-63bits to store integers. Consequently, this function is immune to the
Geek's Millennium until at least the year 292,000,000,000.
Syntax:UnixTime(datestr,timestr)
Example Usage:x%=UnixTime("20-08-1995","06:00:00")
Function UnixTime(DD$,TT$) As integer
' seconds since 01-01-1970. no checks on the argument format
' DD$ is dd-mm-yyyy TT$ is hh:mm:ss 24h so as returned by DATE$ and TIME$ - ymmv
Local integer n,s,y,m
m=Split(DD$,"-")
If m<>3 then UnixTime=-1:Exit Function
y=Val(SP$(3)):s=0
For n=1970 To y-1
If ((n Mod 4=0) And (n Mod 100 <>0)) Or (n Mod 400=0) Then
s=s+366
Else
s=s+365
EndIf
Next
For n=1 To Val(SP$(2))-1
Select Case n
Case 1,3,5,7,8,10
s=s+31
Case 2
If ((y Mod 4=0) And (y Mod 100 <>0)) Or (y Mod 400=0) Then
s=s+29
Else
s=s+28
EndIf
Case 4,6,9,11
s=s+30
End Select
Next
s=86400*(s+Val(SP$(1))-1)
m=Split(TT$,":")
If m<>3 then UnixTime=-1:Exit Function
s=s+(3600*Val(SP$(1))) + (60*Val(SP$(2))) + Val(SP$(3))
UnixTime=s
End Function