Current Unix Timestamp SECONDS SINCE JAN 01 1970

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

How to convert Datetime to Unix timestamp in Ballerina

🎈 🎈 🎈
+1

    import ballerina/time;

    public function main() {
        time:Utc dateTime = time:utcFromString("2018-01-01 00:00:00", "yyyy-MM-dd HH:mm:ss");
        int unixTimestamp = time:toUnix(dateTime);
        io:println("Unix Timestamp: ", unixTimestamp);
    }            
        

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

Code Explanation

In this Ballerina code for converting a date to a Unix timestamp, the time:utcFromString function converts a human-readable date string (2018-01-01 00:00:00) into a time:Utc structure.
The time:toUnix function then converts this Utc structure to a Unix timestamp (an integer representing the number of seconds since the Unix epoch).



Other useful Ballerina date functions

Function Description Example
time:currentTime() Returns the current UTC time as a time:Utc structure. time:currentTime() returns Utc{2024-09-05T14:55:00Z}
time:utcFromUnix(seconds) Converts a Unix timestamp to a time:Utc structure. time:utcFromUnix(1609459200) returns Utc{2021-01-01T00:00:00Z}
time:toUnix(time) Converts a time:Utc structure to a Unix timestamp. time:toUnix(time:currentTime()) returns 1693227296
time:format(time, format) Formats a time:Utc structure into a custom string format. time:format(time:currentTime(), "yyyy-MM-dd HH:mm:ss") returns 2024-09-05 14:55:00
time:addDuration(time, duration) Adds a duration (e.g., hours, minutes) to a time:Utc structure. time:addDuration(time:currentTime(), {hours: 1}) adds 1 hour to the current time.
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