Use the chrono crate to get the current date and time, as the standard library's std::time::SystemTime lacks convenient formatting and calendar methods. You can retrieve the current UTC time or local time using Utc::now() or Local::now(), respectively, and format it as needed.
First, add the dependency to your Cargo.toml:
[dependencies]
chrono = "0.4"
Here is a practical example showing how to get the current time in UTC and format it, as well as how to get the local time:
use chrono::{Local, Utc, DateTime};
fn main() {
// Get current UTC time
let now_utc: DateTime<Utc> = Utc::now();
println!("UTC: {}", now_utc.format("%Y-%m-%d %H:%M:%S"));
// Get current local time
let now_local: DateTime<Local> = Local::now();
println!("Local: {}", now_local.format("%Y-%m-%d %H:%M:%S"));
// Extract specific components
let year = now_local.year();
let month = now_local.month();
let day = now_local.day();
println!("Today is {}/{}/{}", day, month, year);
}
If you need a timestamp (seconds since the Unix epoch) instead of a formatted date, use timestamp() on the DateTime object or SystemTime::now() from the standard library. The standard library approach is lighter but requires manual conversion for human-readable strings:
use std::time::{SystemTime, UNIX_EPOCH};
fn main() {
let start = SystemTime::now();
let since_the_epoch = start
.duration_since(UNIX_EPOCH)
.expect("Time went backwards")
.as_secs();
println!("Unix timestamp: {}", since_the_epoch);
}
For most application logic involving dates, chrono is the standard choice because it handles time zones, leap years, and formatting out of the box. If you are building a minimal binary and only need a raw timestamp, the standard library SystemTime is sufficient and avoids external dependencies.