Welcome Guest, you are in: Login

Fruit Of The Shed

Navigation (MMBasic)






Search the wiki

»


Page History: UnixTime or Epoch Time

Compare Page Revisions



« Older Revision - Back to Page History - Newer Revision »


Page Revision: 2017/08/03 16:19


Many computer systems store and process time as the elapsed seconds since 00:00:00 01/01/1970 and this method is commonly termed "unixtime".

Unixtime removes much of the hassle with dealing with date formats as they are only converted back to "human readable" when needed and so will use the date format of the locale. Any date numbers you generate can be checked against this web tool. Unixtime is not UTC. It may be, but as it is calculated from local time, it will only be UTC if the time on the relevant system is UTC e.g. raw time from a GPS receiver.

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 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.

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.

A format option allows the date part to be interpretted as follows:
DD-MM-YYYY when opt=0 or omitted
YYYY-MM-DD when opt<>0

The option can be omitted if required

Syntax:
UnixTime(datestr,timestr[,opt])

Example Usage:
x%=UnixTime("20-08-1995","06:00:00")
or
x%=UnixTime("1995-08-20","06:00:00",1)

Dependencies:


	Function UnixTime(DD$,TT$,opt) As integer
  ' seconds since 01-01-1970. no checks on the argument format
  ' DD$ is dd-mm-yyyy or yyyy-mm-dd depending on opt,  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
		If opt=0 then
                    y=Val(SP$(3))
                else
                    y=Val(SP$(1))
                EndIf
                s=0
		For n=1970 To y-1
			s=s+365+IsLeapYear(n)
		Next
		For n=1 To Val(SP$(2))-1
			Select Case n
				Case 1,3,5,7,8,10
					s=s+31
				Case 2					
					s=s+28+IsLeapYear(y)					
				Case 4,6,9,11
					s=s+30
			End Select
		Next
                If opt=0 Then
                    s=86400*(s+Val(SP$(1))-1)
                Else
                    s=86400*(s+Val(SP$(3))-1)
                EndIf
		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