Current Unix Timestamp SECONDS SINCE JAN 01 1970

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

How to convert Datetime to Unix timestamp in OCaml

🎈 🎈 🎈
+1

    open Unix

    (* Convert Date to Unix timestamp *)
    let tm = {
        tm_sec = 45;
        tm_min = 30;
        tm_hour = 8;
        tm_mday = 15;
        tm_mon = 4;   (* May is the 5th month, but zero-based, so 4 *)
        tm_year = 120; (* 2020 - 1900 *)
        tm_wday = 0;  (* Ignored by mktime *)
        tm_yday = 0;  (* Ignored by mktime *)
        tm_isdst = false;  (* Not using daylight saving time *)
    }
    
    let (unix_timestamp, _) = Unix.mktime tm
    
    let () =
        Printf.printf "Unix Timestamp: %.0f\n" unix_timestamp            
        

Output:
Unix Timestamp: 1586939445
Example only. There may be multiple ways to perform this operation.

Code Explanation

In this Ocaml example, a tm record is created for the date '2020-04-15 08:30:45'. The Unix.mktime function converts this tm record into a Unix timestamp. The output will be the Unix timestamp '1586939445', which is printed using Printf.printf.
The tm_mon and tm_year fields are adjusted (months are zero-based, and the year is counted from 1900).



Other useful OCaml date functions

Function Description Example
Unix.time() Returns the current Unix timestamp (seconds since 1970-01-01). Unix.time() returns 1693227296.0
Unix.gmtime() Converts a Unix timestamp to a tm structure in UTC. Unix.gmtime(1589530245.0) returns the corresponding date and time in UTC.
Unix.localtime() Converts a Unix timestamp to a tm structure in the local time zone. Unix.localtime(1589530245.0) returns the date and time in the local time zone.
Unix.mktime() Converts a tm structure to a Unix timestamp. Unix.mktime(tm) converts a tm structure to a Unix timestamp.
Unix.strftime() Formats a tm structure as a string according to the specified format. Unix.strftime "%Y-%m-%d" tm returns "2020-05-15"
Unix.strptime() Parses a date string into a tm structure using a format string. Unix.strptime "%Y-%m-%d" "2020-05-15" parses the string into a tm structure.
Unix.sleep() Suspends the execution of the program for the specified number of seconds. Unix.sleep(5) suspends the program for 5 seconds.
Unix.gettimeofday() Returns the current time as a floating-point number of seconds since the epoch, including fractional seconds. Unix.gettimeofday() returns 1693227296.123
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