Dates and Time
- Introduction
- The current time
- Formatting dates
- Date arithmetic
- Calendar dates
- Lengths of time
- Parsing dates
- Storing dates
- Testing
Introduction
Web applications constantly work with dates and timestamps, from displaying when a post was published to expiring invitations and trials. Dates in Laravel are the standard library's time values, so they work with every Go library you already use, and you don't need a separate dependency.
Most application code works with three types:
| Type | Use it for |
|---|---|
time.Time | A moment paired with a location, used for formatting, comparisons, and storage (date.Now returns one). |
time.Duration | A length of time, such as a cache entry's lifetime or a job's delay. |
date.Date | A calendar date without a time of day, such as an invoice's due date. |
The date package adds what the standard library leaves out: the current time on a clock your tests can move, checks such as date.IsPast and date.IsToday, month arithmetic that stops at the end of a short month, and relative times such as "3 minutes ago".
The current time
date.Now returns the current time as a time.Time. It reads the application's clock from the context you pass, which in a handler is r, and in a command or a job is its ctx:
import "go.laravel.com/date"
now := date.Now(r)
now.Year() // 2026
now.Month() // October
now.Weekday() // MondayAlways read the time with date.Now, not the standard library's time.Now, so your tests can move the clock. For today's date without a time, call date.Today, which returns a date.Date in the server's location, usually UTC. For today's date in a user's location, call date.TodayIn(r, chicago) instead.
Timezones
Laravel has no application-wide timezone setting. date.Now returns the time in the server's location, which is usually UTC. Keep your dates in UTC while you calculate and store them, and convert them with the time's In method when you show a user their local time:
chicago, err := time.LoadLocation("America/Chicago")
if err != nil {
return web.Fail(err)
}
local := post.CreatedAt.In(chicago)Laravel includes the IANA time zone database in your application's binary, so names such as America/Chicago load even on a server or container that doesn't have one installed.
Formatting dates
To show a date, call its Format method with a layout. A layout is the date January 2, 2006 at 3:04:05 PM, written the way you'd like your date to look:
now := date.Now(r)
now.Format("January 2, 2006") // October 5, 2026
now.Format("Jan 2, 15:04") // Oct 5, 14:30
now.Format("Monday, 3:04 PM") // Monday, 2:30 PM
now.Format(time.DateOnly) // 2026-10-05The time package's documentation lists every layout element and the predefined layouts, such as time.DateOnly and time.RFC3339. A time formats in its own location, so convert it with In first to show a user's local time.
Dates in views
In templates, the date function formats a time with the same layouts, and the forHumans function describes it relative to now, as date.ForHumans does in Go code. Without a layout, date renders times like October 5, 2026. Times display in their own location unless you give a location's name after the layout:
{{/* October 5, 2026 */}}
<time datetime="{{date "2006-01-02T15:04:05Z07:00" .CreatedAt}}">{{date .CreatedAt}}</time>
{{date "Jan 2, 15:04" .CreatedAt}} {{/* Oct 5, 14:30 */}}
{{date "Jan 2, 15:04" "America/Chicago" .CreatedAt}} {{/* Oct 5, 09:30 */}}
{{forHumans .CreatedAt}} {{/* 3 minutes ago */}}Date arithmetic
To find the time two hours from now, call the time's Add method with a time.Duration. For days, call AddDate instead, so adding a day across a daylight saving change keeps the same time of day. Each returns a new time and leaves the original as it was:
now := date.Now(r)
now.Add(2*time.Hour + 30*time.Minute)
now.Add(-15 * time.Minute)
now.AddDate(0, 0, 7) // A week from now
now.AddDate(0, 0, -3) // Three days agoFor months and years, use date.AddMonths and date.AddYears. When the new month is too short for the day, they stop at its last day, so a monthly subscription that started on January 31 renews on February 28. AddDate would overflow into March instead:
renewsAt := date.AddMonths(subscription.StartedAt, 1)
anniversary := date.AddYears(user.CreatedAt, 1)To move a time to the start or end of a period, such as to count the orders placed today, use these functions. Each keeps the time's location, and the time's Truncate method rounds it down to a unit:
date.StartOfDay(now) // October 5, 00:00:00
date.EndOfDay(now) // October 5, 23:59:59.999999999
date.StartOfWeek(now) // Monday, October 5, 00:00:00
date.FirstOfMonth(now) // October 1, 00:00:00
date.LastOfMonth(now) // October 31, 23:59:59.999999999
now.Truncate(time.Minute) // October 5, 14:30:00Comparing dates
To check whether a date has passed, use date.IsPast, or date.IsFuture for one that hasn't come yet. Both compare with date.Now, so they take the context. This handler sends users to the billing page once their 30-day trial is over:
func Show(r *web.Request) *web.Response {
user := r.User[models.User]()
if date.IsPast(r, user.CreatedAt.AddDate(0, 0, 30)) {
return web.Redirect("/billing")
}
return web.View("dashboard", user)
}The other checks are date.IsToday, date.IsTomorrow, date.IsYesterday, date.IsWeekend, and date.IsWeekday. They use the time's own location. Just after midnight UTC, it's still yesterday in Chicago, so convert the time before you ask about a user's day:
date.IsToday(r, user.CreatedAt.In(chicago))To compare two times, use their Before, After, and Equal methods, or date.IsSameDay and date.IsBetween (date.IsBetween includes both ends). Compare times with Equal rather than ==, which also compares their locations:
startsAt := date.Now(r)
endsAt := startsAt.AddDate(0, 0, 7)
if invoice.PaidAt.Before(invoice.DueAt) {
// Paid before the due date...
}
if date.IsSameDay(event.StartsAt, event.EndsAt) {
// Single-day event...
}
if date.IsBetween(date.Now(r), startsAt, endsAt) {
// 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 date.DiffInDays, or the whole months with date.DiffInMonths. The result is negative when the second time is earlier. Both follow the calendar rather than counting hours, so a 23-hour day across a daylight saving change still counts as one day:
trialEndsAt := user.CreatedAt.AddDate(0, 0, 30)
daysLeft := date.DiffInDays(date.Now(r), trialEndsAt)For hours, minutes, and seconds, subtract the times with Sub, which returns a time.Duration:
elapsed := finishedAt.Sub(startedAt)
elapsed.Hours() // 2.5
elapsed.Minutes() // 150date.ForHumans formats a time as a human-readable relative string, in its largest whole unit:
date.ForHumans(r, user.CreatedAt) // 3 minutes ago
date.ForHumans(r, user.CreatedAt.AddDate(0, 0, 30)) // in 4 weeksIn a table or activity feed, use date.CompactForHumans to shorten the unit while keeping ago or in:
date.CompactForHumans(r, user.CreatedAt) // 3m agoTo describe a length of time instead, such as how long an outage lasted, pass a time.Duration to date.DurationForHumans:
date.DurationForHumans(incident.ResolvedAt.Sub(incident.StartedAt)) // 4 minutesCalendar dates
Sometimes you need a day on the calendar with no time of day, such as an invoice's due date or a user's birthday. A time.Time would give the date a time and a location, and converting it to a user's location could move November 20 to the evening of November 19. Use a date.Date instead, which holds only a year, a month, and a day:
type Invoice struct {
ID int64 `json:"id"`
DueOn date.Date `json:"due_on"`
PaidOn *date.Date `json:"paid_on"`
}To ask whether an invoice is overdue for a user, compare its date with today's date in the user's location. Compare dates with ==, Before, and After, and count the days between them with DaysUntil, which is negative when the other date is earlier:
today := date.TodayIn(r, chicago)
overdue := invoice.DueOn.Before(today)
dueToday := invoice.DueOn == today
daysLeft := today.DaysUntil(invoice.DueOn)To move a date, call its AddDays, AddMonths, or AddYears method. AddMonths stops at the end of a short month, as date.AddMonths does for a time. To show a date, call Format with a layout, String for 2026-11-20, or ForHumans for a string such as in 3 days:
invoice.DueOn.AddDays(-3) // 2026-11-17
invoice.DueOn.Format("January 2, 2006") // November 20, 2026
invoice.DueOn.ForHumans(r) // in 3 daysTo get the date of a time, call date.Of(t.In(chicago)), which takes the date in the time's own location. To go the other way, such as to query the orders placed on a day, invoice.DueOn.In(chicago) returns midnight at the start of the date in Chicago.
Lengths of time
Whenever a Laravel function accepts a length of time, such as a cache entry's lifetime or a job's delay, pass a time.Duration like 10 * time.Minute. For example, this handler caches the user count for ten minutes:
import (
"time"
"go.laravel.com/cache"
"go.laravel.com/db"
)
count, err := db.Table("users").Count(r)
if err != nil {
return web.Fail(err)
}
err = cache.Put(r, "users:count", count, 10*time.Minute)Job delays and temporary signed URLs also accept an explicit target time through their Until forms, such as queue.DelayUntil and urls.TemporarySignedRouteUntil.
Configuration holds lengths of time as time.Duration values too, such as your session lifetime, which most applications set in minutes with SESSION_LIFETIME. To set one in code, change its field in your options' Configure function in bootstrap/app.go:
func Options() laravel.Options {
return laravel.Options{
Configure: func(cfg *config.Config, env *config.Env) {
cfg.Session.Lifetime = 2 * time.Hour
},
// ...
}
}To learn more, check out the configuration guide's section on changing Laravel's configuration.
Parsing dates
When dates arrive as text from a form, an API, or a file, parse them with time.Parse and a layout. For a time written without a UTC offset, use time.ParseInLocation with the location the text was written in. For a calendar date, use date.Parse:
publishedAt, err := time.Parse(time.RFC3339, "2026-10-05T19:30:00Z")
meetingAt, err := time.ParseInLocation("01/02/2006 3:04 PM", "10/05/2026 2:30 PM", chicago)
dueOn, err := date.Parse("2026-10-05")To build a time from its calendar parts, such as a meeting scheduled for 2:30 PM in Chicago, use time.Date:
meeting := time.Date(2026, time.October, 5, 14, 30, 0, 0, chicago)Request input binds directly into these types: a time.Time field reads a timestamp with a UTC offset, such as 2026-10-05T19:30:00Z, and a date.Date field reads a date such as 2026-10-05. In a validated form, the date rules check a field's text: Date for a calendar date, DateTime for a timestamp, and DateFormat for text in a layout of your own, which you then parse with time.ParseInLocation.
Storing dates
Store moments such as a post's created_at as time.Time, and convert them to a user's location when you show them. A time.Time field maps to the columns created by Timestamps() and SoftDeletes(), in UTC, and a date.Date field maps to date columns. A column that may be NULL, such as published_at, is a pointer, which reads NULL as nil:
type Post struct {
ID int64 `json:"id"`
Title string `json:"title"`
PublishedOn *date.Date `json:"published_on"`
CreatedAt time.Time `json:"created_at"`
}
recent, err := model.Query[models.Post]().
Where("created_at", ">", date.Now(r).AddDate(0, 0, -7)).
Get(r)By default, Laravel stores times with microsecond precision and truncates outgoing times to that precision before writing them to the database. You may change this with DB_TIME_PRECISION. To learn more, check out the database guide's section on time precision.
A time.Time encodes to JSON as RFC 3339 text, such as "2026-10-05T19:30:00Z", so it round-trips through JSON and Inertia props. To learn how each database stores dates and times, check out the database guide's section on dates, times, and decimals.
Testing
To test code that depends on the time, such as the trial in Comparing dates, move the application's clock forward with the test client's Travel method instead of waiting:
package feature_test
import (
"testing"
"time"
"app/database/factories"
"app/tests"
)
func TestTheDashboardRedirectsToBillingAfterTheTrial(t *testing.T) {
client := tests.New(t)
user := client.Create(factories.User)
client.Travel(31 * 24 * time.Hour)
client.ActingAs(&user).Get("/dashboard").AssertRedirect("/billing")
}For the other clock methods, such as TravelTo and Freeze, and details on how the time stands still after it travels, check out the testing guide's section on time travel.