Get The Current DateTime With The TimeZone Offset In Rust
Introduction
I've got a bunch of posts about Rust's chrono. They've all led to this, which gets me what I'm looking for most of the time.
---
chrono = "0.4.40"
---
use Local;
Output:
2025-04-23T23:48:21-04:00
I swear I all the posts and docs had me running around in circles with NaiveDateTime
and TimeZone
stuff. It's great if you need the complexity. But if I just want to do a date, this is it 99% of the time.
The Different Formats
The above example uses RFC 3339 which is like ISO 8601. The chrono::SecondsFormat::Secs
stuff trims milliseconds. I don't need those most of the time. chrono will output RFC 3339 with the millisconds and RFC 2822 as well. Here's what all three built-in outputs look like:
---
chrono = "0.4.40"
---
use Local;
Output:
Wed, 23 Apr 2025 23:48:21 -0400
2025-04-23T23:48:21.155232-04:00
2025-04-23T23:48:21-04:00
-- end of line --