Current Unix Timestamp SECONDS SINCE JAN 01 1970

Current UTC Time
2025-08-20
Convert Unix Timestamp to Datetime in Forth

How to convert Unix timestamp to Datetime in Forth

🎈 🎈 🎈
+1

    \ Convert Unix timestamp to Date and format as 'YYYY-MM-DD HH:MM:SS'
    : unix-to-date ( unix-timestamp -- year month day hour minute second )
        dup 60 /mod \ seconds
        swap dup 60 /mod \ minutes
        swap dup 24 /mod \ hours
        swap dup 86400 / \ days since epoch
        1970 +  \ simplistic year calculation (not accounting for leap years)
        \ Format output as 'YYYY-MM-DD HH:MM:SS'
        swap >r swap >r swap >r
        r@ . 4 spaces r> 0 . r> 0 . r> 0 . r> ."  " . r> 0 . r> 0 . r> 0 .
    ;
    
    \ Example usage
    299429912 unix-to-date
        

Output:
1979-06-28 14:58:32
Example only. There may be multiple ways to perform this operation.

Code Explanation

In this example of Unix timestamp to date conversion using Forth, the unix-to-date function breaks down the Unix timestamp (which represents seconds since January 1, 1970) into seconds, minutes, hours, and days. The mod operation is used to calculate the remainder of division to get these individual components.
Then, a simple addition is used to calculate the year starting from 1970.
For the Unix timestamp '299429912' the output would be the datetime '1979-06-28 14:58:32'


Other useful Forth date functions

Function Description Example
60 /mod Divides the top of the stack by 60 and leaves the quotient and remainder (used to break down seconds into minutes). 12345 60 /mod returns quotient 205 and remainder 45 (205 minutes, 45 seconds).
86400 * Multiplies a number by the number of seconds in a day (used to calculate total seconds in days). 5 86400 * returns 432000 (5 days in seconds).
365 * 86400 * Calculates the number of seconds in a year (assuming 365 days). 1 365 * 86400 * returns 31,536,000 (one year in seconds).
swap Exchanges the top two elements on the stack (used frequently in date and time calculations). 5 10 swap swaps the top two elements, leaving 10 on top.
dup Duplicates the top stack element. 5 dup leaves two 5s on the stack (5 5).
mod Computes the remainder after division, often used for extracting seconds, minutes, and hours. 125 60 mod returns 5 (remainder after dividing by 60).
+ Adds the top two elements on the stack. 5 3 + returns 8.
- Subtracts the top two elements on the stack. 10 5 - returns 5.
Current Unix Timestamp SECONDS SINCE JAN 01 1970

Current UTC Time
2025-08-20
Ad Banner Placeholder
Ad Banner Placeholder
Ad Banner Placeholder
Ad Banner Placeholder