Dates and Time
- Introduction
- The current time
- Formatting dates
- Date arithmetic
- Lengths of time
- Parsing dates
- Storing dates
- Testing
- Daylight saving
- Common mistakes
Introduction
Web applications constantly work with dates and timestamps, from displaying when a post was published to expiring invitations and trials. dust-framework re-exports the Jiff date and time library as dust::time, so you do not need to add a separate dependency. Jiff handles timezone conversions, daylight saving transitions, and calendar-aware arithmetic (so adding one month to January 31 lands on the end of February).
Most application code works with three types:
| Type | Use it for |
|---|---|
ZonedDateTime |
A moment paired with a timezone, used for formatting and calendar calculations (dust::now() returns one). |
Timestamp |
A timezone-independent instant, ideal for database storage and comparisons. |
civil::Date |
A calendar date without a time of day, such as a birthday. |
The Dates trait in dust::time adds convenience helpers such as is_past, plus, minus, diff_in_days, and format to all three types, and is included in the prelude.
The current time
dust::now() returns the current time as a ZonedDateTime in UTC. You may call it anywhere in your application, such as in a handler or a job:
let now = dust::now();now.year(); // 2026now.date(); // 2026-10-05now.weekday(); // MondayAlways read the time with dust::now(), not Jiff's ZonedDateTime::now() or the standard library's SystemTime::now(), so your tests can move the clock. For today's date without a time, call dust::time::today(), which returns a civil::Date in UTC.
Timezones
dust-framework has no application-wide timezone setting. Its clock, time travel in tests, and scheduled tasks all use UTC. Keep your dates in UTC while you calculate and store them, and convert them with in_tz when you show a user their local time:
let chicago = dust::now().in_tz("America/Chicago")?;Jiff includes the IANA time zone database, so names such as America/Chicago work even on a server that doesn't have one installed.
Formatting dates
To show a date, call format with strftime's % directives:
use dust::time::Dates;let now = dust::now();now.format("%B %-d, %Y"); // October 5, 2026now.format("%b %-d, %H:%M"); // Oct 5, 14:30now.format("%A, %-I:%M %p"); // Monday, 2:30 PMnow.format("%Y-%m-%d"); // 2026-10-05Jiff's documentation lists every directive. format panics on an invalid format, so cover the formats you write with a test. A Timestamp formats in UTC, so convert it with in_tz first to show a user's local time.
Dates in views
In templates, the date filter formats a date with the same directives, and the for_humans filter formats a relative time string matching for_humans in Rust. Without a format, date renders dates like October 5, 2026. Dates display in UTC unless you pass a tz:
<time datetime="{{ post.created_at }}">{{ post.created_at|date }}</time> {# October 5, 2026 #}{{ post.created_at|date("%b %-d, %H:%M") }} {# Oct 5, 14:30 #}{{ post.created_at|date(tz="America/Chicago") }} {# October 5, 2026 #}{{ post.created_at|for_humans }} {# 3 minutes ago #}Date arithmetic
To find the date a week from now or three days ago, call plus or minus with a span. Each returns a new date and leaves the original as it was. ToSpan, which the prelude also imports, builds spans from integers in any unit:
use dust::time::{Dates, ToSpan};let now = dust::now();now.plus(1.week());now.minus(3.days());now.plus(2.hours().minutes(30));now.plus(1.month()); // A month after January 31 is February 28Days, weeks, and months follow the date's timezone, so adding a day across a daylight saving change preserves the same time of day. For spans from user input, use Jiff's checked_add and checked_sub instead, which return an error rather than panicking when the computed date falls outside the years -9999 to 9999.
To move a date to the start or end of a period, such as to count the orders placed today, use these Jiff methods. Each returns a Result:
use dust::time::Unit;now.start_of_day()?;now.end_of_day()?;now.first_of_month()?;now.last_of_month()?;now.round(Unit::Minute)?;Comparing dates
To check whether a date has passed, use is_past, or is_future for one that hasn't come yet. Both compare with dust::now(). This handler sends users to the billing page once their 30-day trial is over:
use dust::prelude::*;pub async fn show(user: Authenticated<User>) -> dust::Result<Response> { if user.created_at.plus(30.days()).is_past() { return Ok(Redirect::to("/billing").into_response()); } Ok(view("dashboard", data! { name => &user.name }).into_response())}The other checks are is_today, is_tomorrow, is_yesterday, is_weekend, and is_weekday. They use a ZonedDateTime's own timezone, and UTC for a Timestamp. Just after midnight UTC, it's still yesterday in Chicago, so convert the date before you ask about a user's day:
user.created_at.in_tz("America/Chicago")?.is_today();To compare two dates, use operators such as < and ==, or is_same_day and is_between (is_between is inclusive of both endpoints):
let starts_at = dust::now();let ends_at = starts_at.plus(7.days());if invoice.paid_at < invoice.due_at { // Paid before the due date...}if event.starts_at.is_same_day(&event.ends_at) { // Single-day event...}if dust::now().is_between(&starts_at, &ends_at) { // Promotion is currently active...}The time between dates
To show how many days a trial has left, count the whole days until it ends with diff_in_days. diff_in_hours, diff_in_minutes, and diff_in_seconds count the other units. The result is negative when the other date is earlier:
let trial_ends_at = user.created_at.plus(30.days());let days_left = dust::now().timestamp().diff_in_days(&trial_ends_at);For a span broken across several units, such as 2 hours and 30 minutes, use Jiff's until and since. Pass a (Unit, &date) tuple when you want to specify the largest unit in the span:
use dust::time::Unit;let elapsed = finished_at.since(&started_at)?;elapsed.get_hours(); // 2elapsed.get_minutes(); // 30let remaining = dust::now().until((Unit::Day, &deadline))?;remaining.get_days(); // 4remaining.get_hours(); // 6for_humans formats a date as a human-readable relative string:
user.created_at.for_humans(); // 3 minutes agouser.created_at.plus(30.days()).for_humans(); // in 4 weeksdust::time::today().for_humans(); // todayIn a table or activity feed, use compact_for_humans to shorten the unit while keeping ago or in:
user.created_at.compact_for_humans(); // 3m agoLengths of time
Whenever a dust-framework API accepts a duration, such as a cache TTL or a job delay, pass a span like 10.minutes(). For example, this caches the user count for ten minutes:
use dust::cache;use dust::time::ToSpan;let count = User::query().count().await?;cache::put("users:count", count, 10.minutes()).await?;Job delays and temporary URL expirations also accept an explicit target date such as dust::now().end_of_day()?.
When dust-framework stores or exposes a configured duration (such as your session lifetime), it uses ExactDuration. You may compare it directly against a span (such as lifetime > 1.hour()), and it dereferences to std::time::Duration for standard library or third-party APIs. To assign one in configuration, call .into() on a span in src/app.rs:
Application::configure() .with_config(|config, _| { config.session.lifetime = 2.hours().into(); })Parsing dates
When dates arrive as strings from a form, API, or file, call parse with the target type:
use dust::time::{Timestamp, ZonedDateTime, civil};let timestamp: Timestamp = "2026-10-05T19:30:00Z".parse()?;let zoned: ZonedDateTime = "2026-10-05T14:30:00-05:00[America/Chicago]".parse()?;let date: civil::Date = "2026-10-05".parse()?;To construct a date from individual calendar components, such as a meeting scheduled for 2:30 PM in Chicago, start from civil::date:
let meeting = civil::date(2026, 10, 5).at(14, 30, 0, 0).in_tz("America/Chicago")?;Request input deserializes directly into these types. In a validated form, a civil::Date field validates calendar dates and a Timestamp field validates timestamps with a UTC offset. For custom formats, apply date_format to a String field and parse it with civil::Date::strptime("%d/%m/%Y", &input)?.
Storing dates
Store instants such as a post's created_at as Timestamp, and convert them to ZonedDateTime when formatting for a user's local timezone. Timestamp maps to the columns created by timestamps() and soft_deletes(), while civil::Date maps to date columns:
use dust::db;use dust::time::{Timestamp, civil::Date};#[derive(db::FromRow)]pub struct Post { pub title: String, pub published_on: Option<Date>, pub created_at: Timestamp,}let recent: Vec<Post> = db::table("posts") .filter(db::col("created_at").gt(dust::now().minus(7.days()).timestamp())) .get() .await?;By default, dust-framework stores timestamps with microsecond precision (6 fractional digits) and truncates outgoing values to that precision before writing them to the database. You can customize this with DB_TIME_PRECISION; see time precision in the database guide for details.
Testing
To test code that depends on the time, such as the trial in Comparing dates, move the application's clock forward with travel instead of waiting:
use app::models::User;use dust::model::create;use dust::testing::prelude::*;#[dust::test]async fn the_dashboard_redirects_to_billing_after_the_trial( app: Application,) -> dust::Result<()> { let user = create!(User { name: "Taylor Otwell", email: "taylor@example.com", password: "password", }) .await?; app.travel(31.days()); app.get("/dashboard").acting_as(&user).await.assert_redirect_to("/billing"); Ok(())}For additional clock helpers and details on freezing time between calls, check out time travel in the testing guide.
Daylight saving
A daylight saving transition makes one local hour disappear and another repeat. Jiff resolves a nonexistent local time forward and an ambiguous one to the earlier offset, so civil::date(2026, 3, 8).at(2, 30, 0, 0).in_tz("America/New_York") lands at 3:30 AM, not 2:30. A repeated hour is why storing a local time without an offset is ambiguous: the same wall clock can mean two instants.
Adding a calendar day with plus(1.day()) keeps the same wall-clock time, so a meeting at 9:00 stays at 9:00 across the change. Adding 24 hours with std::time::Duration moves it to 10:00 or 8:00. Use the calendar span unless you mean an exact elapsed duration.
Common mistakes
| Mistake | Why it hurts | Do this instead |
|---|---|---|
Reading ZonedDateTime::now() or SystemTime::now() |
The test clock can't move it. | Call dust::now(). |
Storing a ZonedDateTime |
The same instant has many representations, and a timezone can change. | Store a Timestamp; convert for display. |
Adding 30 days with Duration |
A day is not always 24 hours across a daylight saving change. | Use plus(30.days()), which is calendar-aware. |
Comparing a Timestamp with a local time |
The timestamp is UTC; the local time is not. | Convert with in_tz(...) first, then compare. |
| Formatting for a user without a timezone | A user in Tokyo sees the server's UTC date. | Pass the user's timezone to in_tz or tz=. |
Parsing user input with unwrap |
A malformed date panics the request. | Parse with ? and return a validation error. |
Using civil::Date for an event time |
A date has no hour or offset; an event needs both. | Use Timestamp or ZonedDateTime for instants. |
Assuming date columns store a timezone |
SQL date has no time or zone. |
Store Timestamp when the time matters. |
The rule that prevents most of these is simple: store instants as Timestamp in UTC, do arithmetic with Dates and ToSpan, and convert to a timezone only when you format or compare against a user's local day.