Timetraveler - crate for converting between time structs
โ Rust ๐ 2025-10-07 ๐ค surdeus ๐๏ธ 5In my project, I'm using Octocrab to talk to the GitHub API. Octocrab uses Chrono for representing times, whereas my project is using Time internally. This led to me having to convert between them a bunch, and I ended up writing a small crate to do that.
So here it is, version 0.2.0 of Timetraveler, which does exactly that (0.1.0 pointed to the wrong repository). I might add conversions for more crates (or std::time) in the future - but I honestly only know of Time and Chrono, so I stuck with those right now.
Usage is pretty simple: you get extension traits for converting to a representation and then an implementation for the respective representation in the other crate.
use timetraveler::{chrono::AsDateTime, time::AsOffsetDateTime};
use time::{macros::datetime, OffsetDateTime};
use chrono::{DateTime, Utc, FixedOffset};
use chrono_tz::{Tz, Europe::Stockholm};
use rxpect::{expect, expectations::EqualityExpectations};
// A time::OffsetDateTime
let dt = datetime!(2024-01-01 12:00:00 +02:00);
// Convert to chrono::DateTime<Utc>
let utc: DateTime<Utc> = dt.as_date_time_utc();
expect(utc.to_rfc3339().as_ref()).to_equal("2024-01-01T10:00:00+00:00");
// Convert to chrono::DateTime<FixedOffset>
let offset: DateTime<FixedOffset> = dt.as_date_time_offset();
expect(offset.to_rfc3339().as_ref()).to_equal("2024-01-01T12:00:00+02:00");
// Convert to chrono::DateTime<Stockholm>
let stockholm: DateTime<Tz> = dt.as_date_time(Stockholm);
expect(stockholm.to_rfc3339().as_ref()).to_equal("2024-01-01T11:00:00+01:00");
// Convert back to time::OffsetDateTime
let roundtrip: OffsetDateTime = stockholm.as_offset_date_time();
expect(roundtrip).to_equal(dt);
There's a post on my blog with some more detailsโor mostly more words, the above example is pretty much everything you need ![]()
1 post - 1 participant
๐ท๏ธ Rust_feed