Dates

laravel-rust-format Alpha Laravel for Rust

Used in production across multiple projects.

Use laravel_rust_format_core::carbon for PHP date letters and Carbon’s English relative times. Use Jiff 1 types directly, including those re-exported by Laravel for Rust under laravel::time.

InputMeaning
jiff::ZonedDateTimeDate and time in its own zone
jiff::TimestampInstant displayed in UTC
jiff::civil::DateTimeWall time interpreted in UTC
jiff::civil::DateMidnight UTC on that date

These types also work by reference. CarbonInput::to_zoned_datetime returns a Result. Jiff’s timestamp range is narrower than its civil range, so a civil date or time outside the UTC timestamp range returns an error. Formatting, comparisons, calendar properties and relative-time helpers propagate that error. Use a named zone when you need its name, its abbreviation or its daylight-saving rules.

Parse dates and timestamps

use jiff::{Timestamp, tz::TimeZone};
use laravel_rust_format_core::carbon;

let paris = TimeZone::get("Europe/Paris").unwrap();
let date = carbon::parse("2024-02-29 12:45:00", &paris, Timestamp::UNIX_EPOCH).unwrap();
assert_eq!(carbon::to_date_time_string_with(&date, carbon::DateTimePrecision::Minute).unwrap(), "2024-02-29 12:45");
assert_eq!(carbon::to_iso_string_keep_offset(&date).unwrap().as_deref(), Some("2024-02-29T12:45:00.000000+01:00"));
assert_eq!(carbon::create_from_format("!Y-m", "2024-02", &paris).unwrap().day(), 1);
assert_eq!(carbon::create_from_timestamp(-0.25, &TimeZone::UTC).unwrap().subsec_nanosecond(), 750_000_000);

parse accepts PHP's free-form date grammar, including ISO week dates, English month names, time zones and relatives like next Friday noon. It also accepts RFC 9557 bracketed zones. The supplied clock freezes Carbon's relative expressions. modify uses its input date as the clock and preserves the receiver's zone for ordinary modifiers. create_from_timestamp takes integer or float Unix seconds and rounds floats to microseconds.

use jiff::{civil::date, tz::TimeZone};
use laravel_rust_format_core::carbon;

let base = date(2024, 1, 31).at(8, 15, 0, 0);
let friday = carbon::parse("next Friday noon", &TimeZone::UTC, base).unwrap();
assert_eq!(carbon::to_date_time_string(friday).unwrap(), "2024-02-02 12:00:00");

let rolled = carbon::modify(base, "+1 month").unwrap();
assert_eq!(carbon::to_date_time_string(rolled).unwrap(), "2024-03-02 08:15:00");

For PHP's constructor and Unix-seconds interfaces, see PHP functions. The parity guide lists grammar coverage and limits.

create_from_format reads numeric and named dates, clock fields, offsets and IANA zone names with PHP’s pattern letters. The supported letters are d j D l S z F M m n X x Y y a A g h G H i s u v e O P p T U c. Use ! to reset fields parsed to that point and initialize missing fields to the epoch. Use | to apply epoch defaults only to unparsed fields. With an explicit clock, create_from_format_with_now can inherit omitted fields. Input with unconsumed trailing data returns the diagnostic Trailing data. The + modifier permits that suffix.

PHP date letters

Pass the PHP pattern directly to carbon::format(date, pattern). PHP patterns use bare letters such as Y-m-d. A backslash escapes the next character, a final backslash emits a NUL byte, and unrecognized characters are copied through.

use jiff::civil::date;
use laravel_rust_format_core::carbon;

assert_eq!(carbon::format(date(2027, 1, 1), r"o-\WW").unwrap(), "2026-W53");
assert_eq!(carbon::format(date(2026, 12, 3), "l jS F").unwrap(), "Thursday 3rd December");

The example values below use 2026-12-03T14:30:07.123456+01:00[Europe/Amsterdam].

LetterMeaningExample
dDay of month, two digits03
DWeekday abbreviationThu
jDay of month3
lFull weekday nameThursday
NISO weekday, Monday = 14
SEnglish ordinal suffixrd
wWeekday number, Sunday = 04
zDay of year, January 1 = 0336
WISO week number, two digits49
FFull month nameDecember
mMonth number, two digits12
MMonth abbreviationDec
nMonth number12
tNumber of days in the month31
LLeap year flag0
oISO week-numbering year2026
XYear with an explicit sign+2026
xYear with a sign when expansion requires it2026
YYear, at least four digits2026
yTwo-digit year26
aLowercase meridiempm
AUppercase meridiemPM
BSwatch Internet Time in whole beats604
gHour on a 12-hour clock2
GHour on a 24-hour clock14
hHour on a 12-hour clock, two digits02
HHour on a 24-hour clock, two digits14
iMinute, two digits30
sSecond, two digits07
uFractional second in microseconds, six digits123456
vFractional second in milliseconds, three digits123
eTime zone identifierEurope/Amsterdam
ITime zone daylight saving flag0
OUTC offset without a colon+0100
PUTC offset with a colon+01:00
pColonized offset, with Z for UTC+01:00
TTime zone abbreviationCET
ZOffset in seconds east of UTC3600
cISO 8601 date and time2026-12-03T14:30:07+01:00
rRFC 2822 date and timeThu, 03 Dec 2026 14:30:07 +0100
UWhole Unix seconds, rounded down1796304607

Carbon string conversions

The helpers below use the same Amsterdam input. They return Result<String>. The exception is to_iso_string, which returns Result<Option<String>> and uses Ok(None) for local year zero. to_iso_string converts to UTC. The other helpers keep the input zone.

Carbon methodRust helperOutput
toIso8601String()to_iso8601_string2026-12-03T14:30:07+01:00
toISOString()to_iso_string2026-12-03T13:30:07.123456Z
toDateString()to_date_string2026-12-03
toTimeString()to_time_string14:30:07
toDateTimeString()to_date_time_string2026-12-03 14:30:07
toAtomString()to_atom_string2026-12-03T14:30:07+01:00
toRfc2822String()to_rfc2822_stringThu, 03 Dec 2026 14:30:07 +0100
toFormattedDateString()to_formatted_date_stringDec 3, 2026
toDayDateTimeString()to_day_date_time_stringThu, Dec 3, 2026 2:30 PM
toCookieString()to_cookie_stringThursday, 03-Dec-2026 14:30:07 CET
toRssString()to_rss_stringThu, 03 Dec 2026 14:30:07 +0100
toW3cString()to_w3c_string2026-12-03T14:30:07+01:00

For a different fractional precision, use format with u for microseconds or v for milliseconds. Both truncate extra digits.

Relative time with diff_for_humans

The core always takes a comparison instant. Use Relative::Now(now) for the omitted PHP argument, or Relative::To(&other) when the PHP call passed a date. The interval is calendar-aware and is calculated in the subject’s zone. The default displays one part, down to seconds.

use laravel_rust_format_core::carbon::{DiffForHumans, Relative, diff_for_humans};

let now: jiff::ZonedDateTime = "2026-12-03T14:30:00+00:00[UTC]".parse().unwrap();
let date = jiff::civil::date(2026, 12, 3).at(12, 0, 0, 0);
assert_eq!(diff_for_humans(date, Relative::To(&now)).unwrap(), "2 hours before");
assert_eq!(diff_for_humans(date, Relative::Now(now.clone())).unwrap(), "2 hours ago");
assert_eq!(
    DiffForHumans::new().parts(2).join().apply(date, Relative::Now(now)).unwrap(),
    "2 hours and 30 minutes ago",
);

The comparison instant and the wording are independent. Set the wording with syntax.

Carbon syntaxRustWording
Auto (0)DiffSyntax::AutoClock wording for Now, comparison wording for To
Absolute (1)DiffSyntax::Absolute or .absolute()Quantity and unit
Relative to now (2)DiffSyntax::RelativeToNowago or from now
Relative to other (3)DiffSyntax::RelativeToOtherbefore or after
Carbon optionBuilder methodEffect
short.short()Compact unit labels
parts.parts(n)Maximum part count. Use -1 for all parts as in Carbon’s options array.
join.join(), .join_with(glue), .join_with_last(glue, last), .join_using(&callback)English conjunction, custom separators, or a Rust callback. The default is space-separated.
aUnit.a_unit()Uses English articles for singular units where Carbon does.
minimumUnit.minimum_unit(unit)Sets the smallest displayed unit and the unit used for an empty difference.
skip.skip(&units)Skips selected units using their names, plurals or shortcuts.

options(mask) replaces the flag mask. These methods set individual flags.

FlagBuilder methodEffect
NO_ZERO_DIFF (1).no_zero_diff()Uses one unit for an empty difference.
JUST_NOW (2).just_now()Uses just now for an empty clock-relative difference.
ONE_DAY_WORDS (4).one_day_words()Uses yesterday or tomorrow in long, single-part clock wording.
TWO_DAY_WORDS (8).two_day_words()Uses before yesterday or after tomorrow in long, single-part clock wording.
SEQUENTIAL_PARTS_ONLY (16).sequential_parts_only()Stops after the first missing unit once output has begun.
ROUND (32).round()Rounds excess parts to the nearest, with ties up.
FLOOR (64).floor()Rounds down on Carbon’s reference calendar.
CEIL (128).ceil()Rounds excess parts up.

When multiple rounding flags are set, ROUND takes precedence, then CEIL, then FLOOR. Rounding uses the full interval before the display cutoff, including fractional seconds. Known time zone differences

Calendar arithmetic and comparisons

Calendar functions live in laravel_rust_format_core::carbon and accept any CarbonInput. Pass a Jiff ZonedDateTime when the zone matters. Civil dates and timestamps are interpreted in UTC. Pass dates by reference to keep using the originals.

use jiff::civil::date;
use laravel_rust_format_core::carbon::{add_months, add_months_no_overflow, end_of_month};

let jan_31 = date(2024, 1, 31);
assert_eq!(add_months(jan_31, 1).unwrap().date(), date(2024, 3, 2));
assert_eq!(add_months_no_overflow(jan_31, 1).unwrap().date(), date(2024, 2, 29));
assert_eq!(
    end_of_month(date(2024, 2, 1)).unwrap().datetime().to_string(),
    "2024-02-29T23:59:59.999999",
);

Whole calendar days normally preserve the local time on the clock. Hours represent elapsed time, so 24 hours can land at a different local time. Fractional days apply the whole calendar days first, then add the fractional remainder as elapsed time.

use jiff::ZonedDateTime;
use laravel_rust_format_core::carbon::{
    DifferenceOptions, add_days, add_hours, diff_in_days, diff_in_days_with, is_tomorrow,
};

let now: ZonedDateTime = "2024-03-10T00:00:00-05:00[America/New_York]".parse().unwrap();
let tomorrow = add_days(&now, 1).unwrap();
assert_eq!(tomorrow.hour(), 0);
assert_eq!(add_hours(&now, 24).unwrap().hour(), 1);
assert!(is_tomorrow(&tomorrow, &now).unwrap());
assert_eq!(diff_in_days(&tomorrow, &now).unwrap(), -1.0);
assert_eq!(
    diff_in_days_with(&now, &tomorrow, DifferenceOptions::default().utc(true)).unwrap(),
    23.0 / 24.0,
);

Use a CalendarUnit to dispatch at runtime. The supported units vary by operation. For example, Carbon can add a century, but its diffInUnit() has no century unit. DifferenceOptions::default() uses signed results and Carbon's default zone handling. The filtered weekday and weekend-day functions return integer counts.

Localized formats and relative times

Carbon offers two format languages. iso_format uses Moment-style tokens and escapes literal text with brackets. translated_format uses PHP date() letters and translates month names, weekday names, meridiems and ordinal suffixes. Both helpers use English by default. Pass a Locale to the corresponding _in helper to select a translation for a single call.

use laravel_rust_format_core::carbon::{
    Locale, Relative, calendar_in, diff_for_humans_in, iso_format, translated_format_in,
};

let day = jiff::civil::date(2024, 2, 29);
let time = day.at(14, 30, 0, 0);
let french = Locale::new("fr");
let russian = Locale::new("ru");

assert_eq!(iso_format(time, "dddd, MMMM Do [at] LT").unwrap(), "Thursday, February 29th at 2:30 PM");
assert_eq!(translated_format_in(russian, day, "j F").unwrap(), "29 февраля");
assert_eq!(calendar_in(french, time, day).unwrap(), "Aujourd’hui à 14:30");

let now = "2024-02-29T14:30:00+00:00[UTC]".parse().unwrap();
let earlier = day.at(12, 30, 0, 0);
assert_eq!(diff_for_humans_in(french, earlier, Relative::Now(now)).unwrap(), "il y a 2 heures");

Month and weekday forms can depend on the full format. For example, Polish MMMM yields luty, while D MMMM yields 29 lutego on February 29. Carbon's e token numbers weekdays from Sunday. Locale week settings apply to w and g families.

calendar uses the subject's time zone to interpret the comparison date. Use Relative::To for localized before/after wording or Relative::Now for localized ago/from-now wording. References are explicit and the results are independent of the system clock. Select the same locale on DiffForHumans to combine precision, joining, tense and short forms.

use laravel_rust_format_core::carbon::{DiffForHumans, Locale, Relative};
let other = "2024-02-29T14:30:00+00:00[UTC]".parse().unwrap();
let earlier = jiff::civil::date(2024, 2, 29).at(12, 0, 0, 0);
assert_eq!(
    DiffForHumans::new().locale(Locale::new("fr")).parts(2).join()
        .apply(earlier, Relative::To(&other)).unwrap(),
    "2 heures et 30 minutes avant",
);

Community package, not affiliated with Laravel.

Durations and date periods

Interval preserves Carbon's component fields, including unbalanced units and the invert flag. Cascade explicitly to carry between units. Carbon counts four weeks per month when cascading. To specify a different ratio, pass a CascadeFactors value to cascade_with or total_with.

use laravel_rust_format_core::carbon::{CalendarUnit, DiffForHumans, Interval, Locale};

let duration = Interval::minutes(90).cascade()?;
let options = DiffForHumans::for_interval().join().locale(Locale::new("fr"));
assert_eq!(duration.for_humans(&options)?, "1 heure et 30 minutes");
assert_eq!(duration.format("%H:%I"), "01:30");
assert_eq!(duration.total(CalendarUnit::Hour)?, 1.5);
# Ok::<(), laravel_rust_format_core::Error>(())

Use Interval::from_spec for ISO duration designators, from_string for compact English units such as 2h 5m, or from_parts to supply the raw fields. The default spec() drops the invert flag and microseconds. The two switches to spec_with request those components using Carbon's serialization rules.

diff(a, b) and diff_as_carbon_interval(a, b, absolute) return the native calendar fields in the first date's time zone. format("%a") prints total days, and total uses the original endpoints where available.

Use Interval::from(span) and Span::try_from(interval) to move between Jiff and Carbon units. Weeks collapse into days, and the conversion to Jiff requires a common sign on all fields. Diff metadata stays with the interval.

use jiff::civil::date;
use laravel_rust_format_core::carbon::{Period, diff};

assert_eq!(diff(date(2024, 1, 31), date(2024, 3, 1))?.format("%m months %d days (%a total)"),
           "1 months 1 days (30 total)");
let period = Period::from_spec("R3/2024-01-31/P1M")?;
let dates = period.to_array()?;
assert_eq!(dates[1].date(), date(2024, 3, 2));
# Ok::<(), laravel_rust_format_core::Error>(())

A period can have a recurrence count, an end, or both. The count describes yielded dates, including after excluding the start. Calendar-only steps keep local time across DST. Periods with time fields step in UTC and return dates in the original zone. A caller can use iter_capped with an open period. The to_array method applies the crate's collection budget.

shift_timezone keeps the clock fields when changing zones. Use start_of_week_in, end_of_week_in and week_of_year_in for locale-specific weeks, or iso_week_of_year for the ISO week number.