Current Unix Timestamp SECONDS SINCE JAN 01 1970

Current UTC Time
2025-08-21
Convert Unix Timestamp to Datetime in Vala

How to convert Unix timestamp to Datetime in Vala

🎈 🎈 🎈
+1

    void main () {
        int64 unix_timestamp = 1299262391;
    
        // Convert Unix timestamp to GLib.DateTime
        GLib.DateTime date = GLib.DateTime.new_from_unix_local(unix_timestamp);
    
        // Format the date to a readable string
        string formatted_date = date.format("%Y-%m-%d %H:%M:%S");
    
        print("Converted Date: %s\n", formatted_date);
    }            
        

Output:
Converted Date: 2011-03-04 18:13:11
Example only. There may be multiple ways to perform this operation.

Code Explanation

To convert a Unix timestamp to a date in Vala we can use GLib.DateTime.new_from_unix_local(unix_timestamp) which converts the Unix timestamp (eg 1299262391) to a GLib.DateTime object, interpreting the timestamp in the local time zone. Then then format() method is used to convert the DateTime object into a human-readable string with date.format("%Y-%m-%d %H:%M:%S").
The result, which in this illustration is 2011-03-04 18:13:11, is printed using print.


Other useful Vala date functions (GLib.DateTime)

Function Description Example
GLib.DateTime.new_from_unix_local() Creates a DateTime object from a Unix timestamp, interpreted as local time. GLib.DateTime.new_from_unix_local(1514764800) returns 2018-01-01 00:00:00
GLib.DateTime.to_unix() Converts a DateTime object to a Unix timestamp. date.to_unix() returns 1531656645
GLib.DateTime.new_local() Creates a new DateTime object with the specified date and time in the local time zone. GLib.DateTime.new_local(2018, 7, 15, 12, 30, 45) creates the 2018-07-15 12:30:45 date.
GLib.DateTime.format() Formats a DateTime object as a string according to a specified format. date.format("%Y-%m-%d %H:%M:%S") returns 2018-07-15 12:30:45
GLib.DateTime.now_local() Returns the current date and time as a DateTime object in the local time zone. GLib.DateTime.now_local() returns the current date and time.
Current Unix Timestamp SECONDS SINCE JAN 01 1970

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