KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Convert UNIX Epoch time to a ISO Date Time String
PRODUCT: 4D | VERSION: v16, v15, v14, v13 | PLATFORM: Mac & Win
Published On: September 30, 2016

When receiving a date value from a external source it may arrive in the form of a Unix Epoch, aka POSIX, time. Unix Epoch is used by Unix and Unix-like systems (Linux, Mac OS X), and programming languages: most C/C++ implementations, Java, JavaScript, Perl, PHP, Python, Ruby, Tcl, ActionScript.

Unix Epoch time arrives as the number of seconds (e.g. 1474645200) since January 1, 1970. The utility below takes the Unix Epoch time value and converts it to a ISO Datetime string, for example, 1474645200 is converted to 2016-09-23T15:40:00.

$ISO_DtTi_T:=UTIL_UNIX_Epoch_Time_To_ISO_DTS (1474645200)

If (True)
    If (False)
       Begin SQL
       /*
       Name: UTIL_UNIX_Epoch_Time_To_ISO_DTS
       Path: UTIL_UNIX_Epoch_Time_To_ISO_DTS
      
       Purpose: Convert Unix Epoch, aka POSIX, time into an ISO Date time string
      
       $1 - Longint - Seconds since 1/1/1970 to covert
        */
       End SQL
    End if
    //===================== Declare Variables ==================================
    //method_parameters_declarations
    C_TEXT($0;$ISO_DTS_T)
    C_LONGINT($EpochDtTi_L;$1)
    //--------------------------------------------------------------------------
    //local_variable_declarations
    C_LONGINT($Ndx;$SOA;$RIS;$Params_L;$SecsPerDay_L;$SecToToday_L;\
       $Rem_L;$SecPerHr_L;$SecPerMin_L)
    C_DATE($EPOCH_Date_D;$Today_D)
    C_TIME($Time_H)
   
End if
//====================== Initialize and Setup ================================

$Params_L:=Count parameters
If ($Params_L>0)
    $EpochDtTi_L:=$1
    $Epoch_Date_D:=Date("1/1/1970")
   
    $SecPerMin_L:=60
    $SecPerHr_L:=$SecPerMin_L*60
    $SecsPerDay_L:=$SecPerHr_L*24
   
    //======================== Method Actions ==================================
   
    // Longint division
    //
    $SecToToday_L:=$EpochDtTi_L\$SecsPerDay_L
   
    $Today_D:=Add to date($Epoch_Date_D;0;0;$SecToToday_L)
   
    $Rem_L:=$EpochDtTi_L-($SecToToday_L*$SecsPerDay_L)
    $Time_H:=Time($Rem_L)
    $ISO_DTS_T:=String($Today_D;ISO date;$Time_H)
   
    //======================== Clean up and Exit =================================
   
    $0:=$ISO_DTS_T
   
End if