# Dates and Time

- [Introduction](#introduction)
- [The current time](#the-current-time)
    - [Timezones](#timezones)
- [Formatting dates](#formatting-dates)
    - [Dates in views](#dates-in-views)
- [Date arithmetic](#date-arithmetic)
    - [Comparing dates](#comparing-dates)
    - [The time between dates](#the-time-between-dates)
- [Lengths of time](#lengths-of-time)
- [Parsing dates](#parsing-dates)
- [Storing dates](#storing-and-serializing-dates)
- [Testing](#testing)

<a name="introduction"></a>

## Introduction


웹 애플리케이션은 게시물 게시 시각 표시부터 초대와 체험 기간 만료까지 날짜와 타임스탬프를 끊임없이 다룹니다. Laravel은 [Jiff](https://docs.rs/jiff) 날짜·시간 라이브러리를 `laravel::time`으로 다시 내보내므로 별도 의존성을 추가할 필요가 없습니다. Jiff는 시간대 변환, 일광 절약 시간 전환, 달력을 고려한 연산을 처리합니다. 예를 들어 1월 31일에 한 달을 더하면 2월의 마지막 날이 됩니다.


대부분의 애플리케이션 코드는 다음 세 타입을 사용합니다.

| 타입 | 용도 |
| --- | --- |
| `ZonedDateTime` | 시간대와 결합된 시점으로, 형식 지정과 달력 계산에 사용합니다(`laravel::now()`의 반환 타입). |
| `Timestamp` | 시간대에 독립적인 시점으로, 데이터베이스 저장과 비교에 적합합니다. |
| `civil::Date` | 생일처럼 시간이 없는 달력 날짜입니다. |


`laravel::time`의 `Dates` 트레이트는 세 타입 모두에 `is_past`, `plus`, `minus`, `diff_in_days`, `format` 같은 편의 헬퍼를 추가하며 [prelude](/rust/docs/prelude)에 포함됩니다.

<a name="the-current-time"></a>

## The current time


`laravel::now()`는 현재 UTC 시각을 `ZonedDateTime`으로 반환합니다. 핸들러나 잡 등 애플리케이션 어디서나 호출할 수 있습니다.

```rust
let now = laravel::now();

now.year();          // 2026
now.date();          // 2026-10-05
now.weekday();       // Monday
```


[tests](#testing)에서 시계를 이동할 수 있도록 Jiff의 `ZonedDateTime::now()`나 표준 라이브러리의 `SystemTime::now()` 대신 항상 `laravel::now()`로 시간을 읽으세요. 시간 없이 오늘 날짜만 필요하면 UTC의 `civil::Date`를 반환하는 `laravel::time::today()`를 호출하세요.

<a name="timezones"></a>

### Timezones


Laravel에는 애플리케이션 전체의 시간대 설정이 없습니다. 시계, 테스트의 시간 이동, [scheduled tasks](/rust/docs/scheduling#timezones)는 모두 UTC를 사용합니다. 계산하고 저장할 때는 날짜를 UTC로 유지하고, 사용자에게 현지 시각을 보여줄 때 `in_tz`로 변환하세요.

```rust
let chicago = laravel::now().in_tz("America/Chicago")?;
```


Jiff에는 IANA 시간대 데이터베이스가 포함되어 있으므로 서버에 해당 데이터베이스가 없어도 `America/Chicago` 같은 이름을 사용할 수 있습니다.

<a name="formatting-dates"></a>

## Formatting dates


날짜를 표시하려면 `strftime`의 `%` 지시자를 지정하여 `format`을 호출하세요.

```rust
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 문서에 [every directive](https://docs.rs/jiff/latest/jiff/fmt/strtime/)가 정리되어 있습니다. 잘못된 형식을 지정하면 `format`이 패닉을 일으키므로 사용하는 형식을 테스트하세요. `Timestamp`는 UTC로 형식화되므로 사용자 현지 시각을 표시하려면 먼저 `in_tz`로 변환하세요.

<a name="dates-in-views"></a>

### Dates in views


[templates](/rust/docs/templates)에서 `date` 필터는 같은 지시자로 날짜를 형식화하고, `for_humans` 필터는 Rust의 [`for_humans`](#the-time-between-dates)와 같은 상대 시간 문자열을 만듭니다. 형식을 지정하지 않으면 `date`는 `October 5, 2026` 같은 형태로 날짜를 표시합니다. `tz`를 전달하지 않으면 UTC로 표시됩니다.

```html
<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 #}
```

<a name="date-arithmetic"></a>

## Date arithmetic


일주일 뒤나 사흘 전의 날짜를 구하려면 기간을 전달해 `plus`나 `minus`를 호출하세요. 둘 다 원본을 변경하지 않고 새 날짜를 반환합니다. prelude에 포함된 `ToSpan`으로 정수를 원하는 단위의 기간으로 만들 수 있습니다.

```rust
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());   // A month after January 31 is February 28
```


일, 주, 월 연산은 날짜의 시간대를 따르므로 일광 절약 시간 전환을 가로질러 하루를 더해도 같은 시각을 유지합니다. 사용자 입력에서 만든 기간에는 Jiff의 `checked_add`와 `checked_sub`를 사용하세요. 계산된 날짜가 -9999년에서 9999년 범위를 벗어나면 패닉 대신 오류를 반환합니다.


오늘 접수된 주문 수를 세는 경우처럼 날짜를 기간의 시작이나 끝으로 옮기려면 다음 Jiff 메서드를 사용하세요. 각 메서드는 `Result`를 반환합니다.

```rust
use laravel::time::Unit;

now.start_of_day()?;
now.end_of_day()?;
now.first_of_month()?;
now.last_of_month()?;
now.round(Unit::Minute)?;
```

<a name="comparing-dates"></a>

### Comparing dates


날짜가 지났는지는 `is_past`로, 아직 오지 않았는지는 `is_future`로 확인합니다. 둘 다 `laravel::now()`와 비교합니다. 다음 핸들러는 30일 체험 기간이 끝난 사용자를 결제 페이지로 보냅니다.

```rust
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 자정 직후에는 시카고에서 아직 전날이므로 사용자의 날짜를 확인하기 전에 변환하세요.

```rust
user.created_at.in_tz("America/Chicago")?.is_today();
```


두 날짜를 비교하려면 `<`, `==` 같은 연산자나 `is_same_day`, `is_between`을 사용하세요(`is_between`은 양 끝점을 포함합니다).

```rust
let starts_at = laravel::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 laravel::now().is_between(&starts_at, &ends_at) {
    // Promotion is currently active...
}
```

<a name="the-time-between-dates"></a>

### The time between dates


체험 기간의 남은 일수를 표시하려면 `diff_in_days`로 종료까지 남은 온전한 일수를 계산하세요. 다른 단위는 `diff_in_hours`, `diff_in_minutes`, `diff_in_seconds`로 계산합니다. 비교 대상 날짜가 이전이면 결과가 음수입니다.

```rust
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)` 튜플을 전달합니다.

```rust
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();  // 6
```


`for_humans`는 날짜를 사람이 읽기 쉬운 상대 시간 문자열로 형식화합니다.

```rust
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
```


표나 활동 피드에서는 `compact_for_humans`로 `ago`나 `in`을 유지하면서 단위를 축약할 수 있습니다.

```rust
user.created_at.compact_for_humans();   // 3m ago
```

<a name="lengths-of-time"></a>

## Lengths of time


캐시 TTL이나 잡 지연처럼 Laravel API가 기간을 받는 곳에는 `10.minutes()` 같은 기간을 전달하세요. 예를 들어 다음 코드는 사용자 수를 10분간 캐시합니다.

```rust
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()`처럼 기간과 직접 비교할 수 있으며, 표준 라이브러리나 외부 API에서 사용할 수 있도록 `std::time::Duration`으로 역참조됩니다. [configuration](/rust/docs/configuration)에서 값을 지정하려면 `src/app.rs`의 기간에 `.into()`를 호출하세요.

```rust
Application::configure()
    .with_config(|config, _| {
        config.session.lifetime = 2.hours().into();
    })
```

<a name="parsing-dates"></a>

## Parsing dates


폼, API, 파일에서 날짜가 문자열로 들어오면 대상 타입의 `parse`를 호출하세요.

```rust
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`에서 시작하세요.

```rust
let meeting = civil::date(2026, 10, 5).at(14, 30, 0, 0).in_tz("America/Chicago")?;
```


요청 [input](/rust/docs/requests#retrieving-input)은 이 타입들로 직접 역직렬화됩니다. [validated form](/rust/docs/validation#calendar-dates)에서 `civil::Date` 필드는 달력 날짜를, `Timestamp` 필드는 [timestamps with a UTC offset](/rust/docs/validation#date-times)을 검증합니다. 사용자 지정 형식에는 `String` 필드에 [`date_format`](/rust/docs/validation#date-formats)을 적용하고 `civil::Date::strptime("%d/%m/%Y", &input)?`로 파싱하세요.

<a name="storing-and-serializing-dates"></a>

## Storing dates


게시물의 `created_at` 같은 시점은 `Timestamp`로 저장하고 사용자의 현지 시간대로 표시할 때 `ZonedDateTime`으로 변환하세요. `Timestamp`는 [`timestamps()`](/rust/docs/schema#column-types)와 `soft_deletes()`가 만드는 컬럼에 대응하고, `civil::Date`는 `date` 컬럼에 대응합니다.

```rust
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`으로 변경할 수 있습니다. 자세한 내용은 데이터베이스 가이드의 [time precision](/rust/docs/database#time-precision)을 참고하세요.


Jiff의 타입은 Serde를 지원합니다. `Timestamp`는 `"2026-10-05T19:30:00Z"` 같은 RFC 3339 문자열로 직렬화되므로 JSON과 [Inertia](/rust/docs/inertia) props를 통해 왕복 변환할 수 있습니다. 각 데이터베이스 엔진의 날짜와 타임스탬프 저장 방식은 데이터베이스 가이드의 [dates and timestamps](/rust/docs/database#dates-and-timestamps)를 참고하세요.

<a name="testing"></a>

## Testing


[Comparing dates](#comparing-dates)의 체험 기간처럼 시간에 의존하는 코드를 테스트하려면 기다리는 대신 `travel`로 애플리케이션 시계를 앞으로 이동하세요.

```rust
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(())
}
```


추가 시계 헬퍼와 호출 사이에 시간을 고정하는 방법은 테스트 가이드의 [time travel](/rust/docs/testing#time-travel)을 참고하세요.