日期与时间
简介
Web 应用经常处理日期和时间戳,例如显示文章发布时间,或判断邀请和试用期何时到期。Laravel 通过 laravel::time 重新导出 Jiff 日期时间库,无需另加依赖。Jiff 支持时区转换、夏令时切换和符合日历规则的运算,例如 1 月 31 日加一个月会得到 2 月最后一天。
应用代码主要使用三种类型:
| 类型 | 用途 |
|---|---|
ZonedDateTime | 带时区的时刻,适合格式化和日历计算。laravel::now() 返回此类型。 |
Timestamp | 与时区无关的时刻,适合存入数据库和比较。 |
civil::Date | 仅含年月日的日历日期,例如生日。 |
laravel::time 中的 Dates 特征为这三种类型提供 is_past、plus、minus、diff_in_days 和 format 等辅助方法,已包含在预导入模块中。
当前时间
laravel::now() 以 UTC 时区的 ZonedDateTime 返回当前时间,可以在应用的任何位置调用,例如处理器或作业中:
let now = laravel::now();
now.year(); // 2026
now.date(); // 2026-10-05
now.weekday(); // Monday统一通过 laravel::now() 获取时间,Jiff 的 ZonedDateTime::now() 和标准库的 SystemTime::now() 都会绕过应用时钟,使测试中的时间调整失效。只需今日日期时,调用 laravel::time::today() 获取 UTC 下的 civil::Date。
时区
Laravel 的应用时钟、测试中的时间旅行和调度任务都使用 UTC,没有应用级时区设置。计算和存储时保持 UTC,向用户展示本地时间时再用 in_tz 转换:
let chicago = laravel::now().in_tz("America/Chicago")?;Jiff 自带 IANA 时区数据库,即使服务器未安装该数据库,也能识别 America/Chicago 等名称。
格式化日期
要显示日期,向 format 传入 strftime 的 % 格式指令:
use laravel::time::Dates;
let now = laravel::now();
now.format("%B %-d, %Y"); // October 5, 2026
now.format("%b %-d, %H:%M"); // Oct 5, 14:30
now.format("%A, %-I:%M %p"); // Monday, 2:30 PM
now.format("%Y-%m-%d"); // 2026-10-05完整指令见 Jiff 的格式指令参考。格式无效时 format 会引发 panic,请用测试覆盖你使用的格式。Timestamp 按 UTC 格式化;要显示用户本地时间,先通过 in_tz 转换。
视图中的日期
在模板中,date 过滤器接受相同的格式指令,for_humans 过滤器生成相对时间字符串,与 Rust 中的 for_humans 一致。未指定格式时,date 会渲染出 October 5, 2026 这样的日期。默认使用 UTC,可传入 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 #}日期运算
要计算一周后或三天前的日期,调用 plus 或 minus 并传入时间跨度。两者都会返回新日期,保留原值。预导入模块也导入了 ToSpan,可将整数按所需单位构造成时间跨度:
use laravel::time::{Dates, ToSpan};
let now = laravel::now();
now.plus(1.week());
now.minus(3.days());
now.plus(2.hours().minutes(30));
now.plus(1.month()); // 1 月 31 日加一个月得到 2 月 28 日日、周和月都遵循日期自身的时区,因此跨越夏令时切换时,加一天仍会得到次日相同的本地时间。如果跨度来自用户输入,请使用 Jiff 的 checked_add 和 checked_sub;计算结果超出 -9999 至 9999 年时,两者会返回错误,避免引发 panic。
要将日期移到某个周期的开头或结尾,例如统计今天下的订单,可使用以下 Jiff 方法,均返回 Result:
use laravel::time::Unit;
now.start_of_day()?;
now.end_of_day()?;
now.first_of_month()?;
now.last_of_month()?;
now.round(Unit::Minute)?;比较日期
用 is_past 判断日期是否已过,用 is_future 判断日期是否在将来,两者都与 laravel::now() 比较。以下处理器会在 30 天试用期结束后将用户引导到账单页面:
use laravel::prelude::*;
pub async fn show(user: Authenticated<User>) -> laravel::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())
}其他判断方法有 is_today、is_tomorrow、is_yesterday、is_weekend 和 is_weekday。对 ZonedDateTime 使用值自身的时区,对 Timestamp 使用 UTC。UTC 午夜刚过时,芝加哥仍是前一天,因此要判断用户当地的日期,应先转换时区:
user.created_at.in_tz("America/Chicago")?.is_today();比较两个日期时,可使用 < 和 == 等运算符,或使用 is_same_day 和 is_between(is_between 包含两个端点):
let starts_at = laravel::now();
let ends_at = starts_at.plus(7.days());
if invoice.paid_at < invoice.due_at {
// 在到期日前已付款……
}
if event.starts_at.is_same_day(&event.ends_at) {
// 当天开始并结束的活动……
}
if laravel::now().is_between(&starts_at, &ends_at) {
// 促销正在进行……
}日期之间的时间差
要显示试用期还剩几天,用 diff_in_days 计算距结束还剩多少整天。diff_in_hours、diff_in_minutes、diff_in_seconds 计算对应的其他单位。如果另一个日期更早,结果为负:
let trial_ends_at = user.created_at.plus(30.days());
let days_left = laravel::now().timestamp().diff_in_days(&trial_ends_at);需要将跨度拆成多个单位,例如 2 小时 30 分钟时,使用 Jiff 的 until 和 since。可传入 (Unit, &date) 元组来指定跨度的最大单位:
use laravel::time::Unit;
let elapsed = finished_at.since(&started_at)?;
elapsed.get_hours(); // 2
elapsed.get_minutes(); // 30
let remaining = laravel::now().until((Unit::Day, &deadline))?;
remaining.get_days(); // 4
remaining.get_hours(); // 6for_humans 可以将日期格式化为自然语言表示的相对时间:
user.created_at.for_humans(); // 3 minutes ago
user.created_at.plus(30.days()).for_humans(); // in 4 weeks
laravel::time::today().for_humans(); // today要在表格或动态列表中缩短单位并保留 ago 或 in,可使用 compact_for_humans:
user.created_at.compact_for_humans(); // 3m ago时长
Laravel API 接受时长时,例如缓存 TTL 或作业延迟,可以传入 10.minutes() 这样的时间跨度。例如,以下代码将用户数缓存十分钟:
use laravel::cache;
use laravel::time::ToSpan;
let count = User::query().count().await?;
cache::put("users:count", count, 10.minutes()).await?;作业延迟和临时 URL 的有效期也接受 laravel::now().end_of_day()? 等明确的目标日期。
Laravel 存储或公开配置时长(例如会话有效期)时使用 ExactDuration。它可直接与时间跨度比较,例如 lifetime > 1.hour(),并可解引用为 std::time::Duration,供标准库或第三方 API 使用。要在配置中赋值,请在 src/app.rs 中对时间跨度调用 .into():
Application::configure()
.with_config(|config, _| {
config.session.lifetime = 2.hours().into();
})解析日期
表单、API 或文件中的日期以字符串传入时,可指定目标类型并调用 parse:
use laravel::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()?;要通过各日历组成部分构造日期,例如芝加哥下午 2:30 的会议,可以从 civil::date 开始:
let meeting = civil::date(2026, 10, 5).at(14, 30, 0, 0).in_tz("America/Chicago")?;请求输入可直接反序列化为这些类型。在验证表单中,civil::Date 字段会验证日历日期,Timestamp 字段会验证带 UTC 偏移量的时间戳。对于自定义格式,可在 String 字段上应用 date_format 并使用 civil::Date::strptime("%d/%m/%Y", &input)? 解析。
存储日期
文章的 created_at 等时刻应存储为 Timestamp,按用户当地时区格式化时再转为 ZonedDateTime。Timestamp 对应 timestamps() 和 soft_deletes() 创建的列,civil::Date 对应 date 列:
use laravel::db;
use laravel::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(laravel::now().minus(7.days()).timestamp()))
.get()
.await?;默认情况下,Laravel 以微秒精度(6 位小数)存储时间戳,写入数据库前将值截断到该精度。可用 DB_TIME_PRECISION 自定义,详见数据库指南中的时间精度。
Jiff 的类型支持 Serde。Timestamp 会序列化为 RFC 3339 文本,例如 "2026-10-05T19:30:00Z",可通过 JSON 和 Inertia 属性往返传递。关于各数据库引擎如何存储日期与时间戳,请参阅数据库指南中的日期与时间戳。
测试
测试依赖时间的逻辑时,例如比较日期中的试用期示例,可用 travel 推进应用时钟,无需实际等待:
use app::models::User;
use laravel::model::create;
use laravel::testing::prelude::*;
#[laravel::test]
async fn the_dashboard_redirects_to_billing_after_the_trial(
app: Application,
) -> laravel::Result<()> {
let user = create!(User {
name: "Taylor Otwell",
email: "taylor@laravel.com",
password: "password",
})
.await?;
app.travel(31.days());
app.get("/dashboard").acting_as(&user).await.assert_redirect_to("/billing");
Ok(())
}关于更多时钟辅助方法以及如何在多次调用间冻结时间,请参阅测试指南中的时间旅行。