Limited Offer
60% OFF on all plans!

Date & Time in Go

Complete guide to Go date and time: creating times, timestamps, parsing, formatting, comparison, arithmetic, timezones, UTC vs local, and common backend use cases.

Introduction to Date & Time

Go represents date and time with the time package. A time.Time value is a point in time. Internally it is based on wall clock and monotonic clock; timestamps are often expressed as seconds (or nanoseconds) since the Unix epoch (1 Jan 1970 UTC).

1. What is time.Time?

time.Time is the main type for a moment in time.

Creating time.Time Values

Use time.Now(), time.Date(), time.Unix(), or time.Parse() depending on your input.

1. Current Date & Time

time.Now() for the current moment.

2. Time from Timestamp (Unix)

time.Unix(sec, nsec) for epoch seconds/nanoseconds.

3. Time from Components

time.Date(year, month, day, hour, min, sec, nsec, loc).

4. Time from String (Parse)

time.Parse(layout, value) for ISO and custom formats.

Timestamps

Timestamps are common in databases, logs, and APIs. Go uses seconds or milliseconds since Unix epoch.

1. Getting Current Timestamp

Unix() or UnixMilli().

2. time.Time to Timestamp

Use .Unix() or .UnixMilli() on any time.Time.

Getting Date Components

Use .Year(), .Month(), .Day(), .Hour(), .Minute(), .Second(). For UTC, call .UTC() first or use the same methods on a UTC time.

1. Local Date Components

Methods return values in the time's location.

2. UTC Date Components

Call .UTC() then use the same methods.

Formatting Dates

Use .Format(layout). The layout is the reference time "Mon Jan 2 15:04:05 MST 2006" with your desired format. time.RFC3339 is common for APIs.

1. Format with Layout

Reference time is 2006-01-02 15:04:05.

2. Common Layouts

time.RFC3339, time.DateTime, time.DateOnly.

Comparing Dates

Use .Before(t), .After(t), or .Equal(t). All comparisons are safe and respect the moment in time.

1. Comparing Two Times

.Before(), .After(), .Equal().

Date Arithmetic

Use .Add(duration) and .Sub(other). .Sub returns a time.Duration. time.Duration is in nanoseconds; use time.Hour, time.Minute, etc.

1. Adding / Subtracting Time

.Add() and .Sub().

2. Difference Between Two Times

.Sub() returns time.Duration.

Timezones & UTC

Always be explicit about timezone. Store and compute in UTC; convert to local only at display edges.

1. Local Time vs UTC

time.Local, time.UTC, .In(loc).

Best Practices

Handling date and time correctly is critical in backend systems.

1. Recommended Practices

Rules to follow.