Current Unix Timestamp SECONDS SINCE JAN 01 1970

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

How to convert Unix timestamp to Datetime in Rust

🎈 🎈 🎈
+1

    //First, add the chrono crate to your Cargo.toml:

    [dependencies]
    chrono = "0.4"

    //Then, in your Rust code:

    use chrono::{NaiveDateTime, TimeZone, Utc};

    fn main() {
        let unix_timestamp: i64 = 1366627714; 
        let naive_datetime = NaiveDateTime::from_timestamp(unix_timestamp, 0);
        
        // Convert to UTC
        let datetime_utc = Utc.from_utc_datetime(&naive_datetime);

        println!("Converted Date: {}", datetime_utc);
    }
        

Output:
Converted Date: 2013-04-22 10:48:34
Example only. There may be multiple ways to perform this operation.

Code Explanation

In this Rust code snippet, the Unix timestamp 1366627714 is converted to a NaiveDateTime object using NaiveDateTime::from_timestamp, where the second argument '0' represents nanoseconds (set to 0 for simplicity).
This NaiveDateTime object is then converted to a UTC datetime using Utc.from_utc_datetime. The resulting date and time are printed in a human-readable format, such as 2013-04-22 10:48:34 in this case.


Other useful Rust date functions (with chrono crate)

Function Description Example
NaiveDateTime::from_timestamp() Creates a NaiveDateTime object from a Unix timestamp (seconds since 1970) and nanoseconds. NaiveDateTime::from_timestamp(1514764800, 0) returns 2018-01-01 00:00:00
Utc.from_utc_datetime() Converts a NaiveDateTime object to a UTC datetime. Utc.from_utc_datetime(&naive_datetime) converts 2018-01-01 00:00:00 to UTC.
NaiveDate::from_ymd() Creates a NaiveDate object from the specified year, month, and day. NaiveDate::from_ymd(2018, 7, 15) returns 2018-07-15
NaiveDateTime::and_hms() Adds hours, minutes, and seconds to a NaiveDate to create a NaiveDateTime object. date.and_hms(12, 30, 45) adds time to a date.
NaiveDateTime::timestamp() Returns the Unix timestamp for a NaiveDateTime object. naive_datetime.timestamp() returns 1531656645 for 2018-07-15 12:30:45
NaiveDateTime::format() Formats a NaiveDateTime object as a string. naive_datetime.format("%Y-%m-%d %H:%M:%S") returns 2018-07-15 12:30:45
Utc::now() Returns the current UTC date and time. Utc::now() returns the current UTC date and time.
Local::now() Returns the current local date and time. Local::now() returns the current local date and 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