Current Unix Timestamp SECONDS SINCE JAN 01 1970

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

How to convert Datetime to Unix timestamp in Rust

🎈 🎈 🎈
+1

    use chrono::NaiveDate;

    fn main() {
        // Create a NaiveDate object for 2012-10-11 11:21:46
        let naive_date = NaiveDate::from_ymd(2012, 10, 11).and_hms(11, 21, 46);
    
        // Convert to Unix timestamp
        let unix_timestamp = naive_date.timestamp();
    
        println!("Unix Timestamp: {}", unix_timestamp);
    }            
        

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

Code Explanation

In this example, a NaiveDate object is created for the date '2012-10-11 11:21:46' using NaiveDate::from_ymd, which sets the year, month, and day. The and_hms method adds hours, minutes, and seconds. The timestamp() method then converts the NaiveDateTime object into a Unix timestamp (seconds since 1970-01-01).
The result is printed using the println! function.


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