Go date and time programs work with dates, clocks and durations, such as showing an order date, finding someone’s age or counting days until a deadline. Go’s time package handles all of this, but it has one unusual rule: you format dates with a fixed example date instead of codes like YYYY. In this post, you will write fourteen date and time programs with their exact output, and then practice the time questions that interviewers like to ask.
We already used time briefly in our Go function programs. For the full package tour, read the Go time package guide with examples. Every program here uses fixed dates, so the output stays the same in the Go Playground and on your machine. All programs were tested on Go 1.27.
What are Go Date and Time Programs?
Go date and time programs use the time.Time type for a moment in time and time.Duration for a length of time. A Time holds the date, the clock time and a location, such as UTC or India Standard Time.
Think of time.Time as a stamp on a parcel that says exactly when it was posted and in which city. A time.Duration is the gap between two stamps, like “3 days and 4 hours”.
Why Go Date and Time Programs Matter
Almost every app shows or stores time, so Go date and time programs are worth practising. For example, a shop prints invoice dates, a bank calculates interest days, a gym app tracks workout length and a server logs when each request arrived. Mistakes here cause real bugs, such as wrong ages or deadlines that are off by a day.
- Display: show dates in the format users expect, like 15-08-2026.
- Maths: add days, find differences and work out ages.
- Time zones: store in UTC and show local time to each user.
- Interviews: the layout date, durations and time zone questions are common.
How Go Date and Time Programs Work
Go formats and parses dates using a reference time: Mon Jan 2 15:04:05 MST 2006. Each part has a number that is easy to remember in order: month 1, day 2, hour 3 (15), minute 4, second 5, year 6, zone 7 (MST is -0700). You write a layout that looks like that date, and Go swaps in your real values.

The table below shows the layout parts you will use most.
| You want | Layout part | Example output |
|---|---|---|
| Year | 2006 | 2026 |
| Month number | 01 | 08 |
| Month name | Jan or January | Aug or August |
| Day | 02 | 15 |
| Weekday | Mon or Monday | Sat or Saturday |
| 24-hour clock | 15:04 | 18:30 |
| 12-hour clock | 3:04 PM | 6:30 PM |
| Seconds | 05 | 09 |
Basic Go Date and Time Programs
These first Go date and time programs create and format dates. If you are new to Go, start with Program 1. It is the smallest date program you can write.
Program 1: Your First Date Program
package main
import (
"fmt" // fmt prints text on the screen
"time" // time works with dates, clocks and durations
)
func main() {
// time.Date builds a date: year, month, day, hour, minute, second, nanosecond, zone.
// := creates a new variable and stores the value in it.
independenceDay := time.Date(2026, time.August, 15, 0, 0, 0, 0, time.UTC)
// Format turns the date into text. "02-01-2006" means day-month-year.
fmt.Println("Date:", independenceDay.Format("02-01-2006"))
// Weekday tells you the day of the week for this date.
fmt.Println("Day of week:", independenceDay.Weekday())
}
Date: 15-08-2026
Day of week: Saturday
First, time.Date builds a fixed date and stores it in independenceDay. Then Format prints it in the day-month-year style. Finally, Weekday looks up the day name for you.
Program 2: Create a Date and Read Its Parts
package main
import (
"fmt"
"time"
)
func main() {
// Build 15 August 2026 at 18:30 in UTC.
moment := time.Date(2026, time.August, 15, 18, 30, 0, 0, time.UTC)
// Printing a time directly shows the date, the clock time and the zone.
fmt.Println(moment)
// Each method reads one part of the date.
fmt.Println(moment.Year(), moment.Month(), moment.Day())
fmt.Println(moment.Weekday(), moment.YearDay()) // YearDay is the day number in the year
fmt.Println(moment.Hour(), moment.Minute())
}
2026-08-15 18:30:00 +0000 UTC
2026 August 15
Saturday 227
18 30
time.Date builds any moment you need. After that, small methods like Year, Month and Hour read one part each. YearDay gives the day number in the year, which is 227 here.
Program 3: Format a Date Many Ways
package main
import (
"fmt"
"time"
)
func main() {
moment := time.Date(2026, time.August, 15, 18, 30, 9, 0, time.UTC)
// Each layout is the reference date written in the shape you want.
fmt.Println(moment.Format("02-01-2006")) // day-month-year
fmt.Println(moment.Format("2006/01/02 15:04:05")) // year first, 24-hour clock
fmt.Println(moment.Format("Monday, 2 January 2006")) // full weekday and month names
fmt.Println(moment.Format("Jan 2, 2006 at 3:04 PM")) // 12-hour clock with PM
fmt.Println(moment.Format(time.RFC3339)) // standard format for APIs
// time.DateOnly and time.TimeOnly are ready-made layouts.
fmt.Println(moment.Format(time.DateOnly), moment.Format(time.TimeOnly))
}
15-08-2026
2026/08/15 18:30:09
Saturday, 15 August 2026
Aug 15, 2026 at 6:30 PM
2026-08-15T18:30:09Z
2026-08-15 18:30:09
You pass a layout string to Format, and Go fills in the real values. So 02-01-2006 gives the Indian style day-month-year. time.RFC3339 is the standard for APIs and JSON. time.DateOnly and time.TimeOnly are handy constants added in Go 1.20.
Program 4: Check If a Date Is a Weekend
package main
import (
"fmt"
"time"
)
// isWeekend returns true when the date is a Saturday or a Sunday.
func isWeekend(date time.Time) bool {
day := date.Weekday()
if day == time.Saturday || day == time.Sunday { // || means "or"
return true
}
return false
}
func main() {
// A slice is a list. Here it holds three dates.
dates := []time.Time{
time.Date(2026, time.October, 16, 0, 0, 0, 0, time.UTC),
time.Date(2026, time.October, 17, 0, 0, 0, 0, time.UTC),
time.Date(2026, time.October, 18, 0, 0, 0, 0, time.UTC),
}
// range gives you each date in the list. The _ skips the index we do not need.
for _, date := range dates {
fmt.Println(date.Format("02 Jan 2006"), date.Weekday(), "weekend:", isWeekend(date))
}
}
16 Oct 2026 Friday weekend: false
17 Oct 2026 Saturday weekend: true
18 Oct 2026 Sunday weekend: true
The isWeekend function reads the weekday and compares it with time.Saturday and time.Sunday. Then the loop checks each date in the list. A check like this is handy when you plan deliveries or office work days.
Program 5: Parse a String into a Time
package main
import (
"fmt"
"time"
)
func main() {
// Parse reads text using a layout and returns a time.
// err is the error value. It is nil (empty) when everything worked.
meeting, err := time.Parse("02-01-2006 15:04", "26-01-2027 09:15")
fmt.Println(meeting, err)
// 31 February does not exist, so Parse returns an error.
// The _ throws away the time value because we only want the error.
_, err = time.Parse("02-01-2006", "31-02-2027")
fmt.Println(err)
}
2027-01-26 09:15:00 +0000 UTC <nil>
parsing time "31-02-2027": day out of range
time.Parse takes the layout first and the text second. The layout must match the input shape exactly. Go also checks the date itself, so 31 February is rejected with a clear error.
Date Maths in Go Date and Time Programs
These Go date and time programs add to dates and find gaps between them.
Program 6: Add Days, Months and Hours
package main
import (
"fmt"
"time"
)
func main() {
order := time.Date(2026, time.October, 5, 10, 0, 0, 0, time.UTC)
// AddDate takes years, months and days.
delivery := order.AddDate(0, 0, 7) // 7 days later
warranty := order.AddDate(1, 0, 0) // 1 year later
// Add takes a Duration, such as 36 hours.
reminder := order.Add(36 * time.Hour)
fmt.Println("Delivery:", delivery.Format("02 Jan 2006"))
fmt.Println("Warranty ends:", warranty.Format("02 Jan 2006"))
fmt.Println("Reminder:", reminder.Format("02 Jan 2006 15:04"))
}
Delivery: 12 Oct 2026
Warranty ends: 05 Oct 2027
Reminder: 06 Oct 2026 22:00
AddDate(years, months, days) works with calendar units. On the other hand, Add takes a Duration, such as 36 hours. Both return a new time, so the original order date stays the same.
Program 7: Days Between Two Dates
package main
import (
"fmt"
"time"
)
func main() {
start := time.Date(2026, time.January, 1, 0, 0, 0, 0, time.UTC)
end := time.Date(2026, time.December, 25, 0, 0, 0, 0, time.UTC)
// Step 1: Sub gives the gap between two times as a Duration.
gap := end.Sub(start)
fmt.Println(gap)
// Step 2: turn the gap into hours, then divide by 24 to get days.
hours := gap.Hours()
days := int(hours / 24) // int() drops the decimal part
fmt.Println("Days:", days)
}
8592h0m0s
Days: 358
Sub returns a Duration, which prints in hours. Next, Hours gives that gap as a number. Dividing it by 24 gives whole days.
Program 8: Age Calculator
package main
import (
"fmt"
"time"
)
// age returns how many full years have passed from birth to today.
func age(birth, today time.Time) int {
// Step 1: subtract the birth year from this year.
years := today.Year() - birth.Year()
// Step 2: if this year's birthday has not come yet, take one year away.
if today.YearDay() < birth.YearDay() {
years--
}
return years
}
func main() {
birth := time.Date(1995, time.November, 20, 0, 0, 0, 0, time.UTC)
today := time.Date(2026, time.October, 18, 0, 0, 0, 0, time.UTC)
fmt.Println("Age:", age(birth, today))
birthday := time.Date(2026, time.November, 20, 0, 0, 0, 0, time.UTC)
fmt.Println("Age on 20 Nov 2026:", age(birth, birthday))
}
Age: 30
Age on 20 Nov 2026: 31
We subtract the years, then take one away if this year’s birthday has not come yet. In real code, pass time.Now() as today. Comparing YearDay can be one day off around 29 February in leap years. For that reason, production code often compares month and day instead.
Program 9: Last Day of a Month
package main
import (
"fmt"
"time"
)
// lastDay returns the number of days in the given month.
func lastDay(year int, month time.Month) int {
// Day 0 of next month means "one day before the 1st", which is the last day of this month.
dayBeforeNextMonth := time.Date(year, month+1, 0, 0, 0, 0, 0, time.UTC)
return dayBeforeNextMonth.Day()
}
func main() {
fmt.Println(lastDay(2026, time.February), lastDay(2028, time.February))
fmt.Println(lastDay(2026, time.April), lastDay(2026, time.December))
}
28 29
30 31
time.Date fixes values that are out of range. So day 0 of March becomes the last day of February. As a bonus, this also handles leap years for free.
Durations in Go Date and Time Programs
These Go date and time programs measure and compare lengths of time.
Program 10: Work with Durations
package main
import (
"fmt"
"time"
)
func main() {
// A Duration is built from units like time.Hour and time.Minute.
workout := 1*time.Hour + 25*time.Minute + 30*time.Second
fmt.Println(workout)
fmt.Println(workout.Minutes()) // the whole duration in minutes
fmt.Printf("%.1f hours\n", workout.Hours()) // %.1f prints one decimal place
// ParseDuration reads a duration from text.
trip, err := time.ParseDuration("2h45m")
fmt.Println(trip, err, trip > workout) // durations can be compared with > and <
}
1h25m30s
85.5
1.4 hours
2h45m0s <nil> true
A Duration is just a number of nanoseconds. So you can add, compare and print it like a number. ParseDuration reads strings like “90s” or “2h45m”.
Program 11: Compare Two Times
package main
import (
"fmt"
"time"
)
func main() {
deadline := time.Date(2026, 10, 20, 17, 0, 0, 0, time.UTC)
submitted := time.Date(2026, 10, 20, 16, 45, 0, 0, time.UTC)
fmt.Println("On time:", submitted.Before(deadline)) // true if submitted is earlier
fmt.Println("Late:", submitted.After(deadline)) // true if submitted is later
fmt.Println("Margin:", deadline.Sub(submitted)) // how much time was left
// Compare gives -1 (earlier), 0 (same) or 1 (later).
fmt.Println(deadline.Compare(submitted))
}
On time: true
Late: false
Margin: 15m0s
1
Before and After answer simple yes or no questions. Compare returns -1, 0 or 1, just like cmp.Compare. It was added in Go 1.20 and works well with slices.SortFunc.
Time Zones in Go Date and Time Programs
Program 12: Convert Between UTC and IST
package main
import (
"fmt"
"time"
)
func main() {
// FixedZone makes a zone with a name and an offset in seconds.
// IST is 5 hours 30 minutes ahead of UTC.
ist := time.FixedZone("IST", 5*3600+30*60)
meeting := time.Date(2026, 10, 20, 9, 30, 0, 0, time.UTC)
// In shows the same moment in another zone.
fmt.Println("UTC:", meeting.Format("15:04 MST"))
fmt.Println("IST:", meeting.In(ist).Format("15:04 MST"))
// A time made in IST can be turned back into UTC.
istMeeting := time.Date(2026, 10, 20, 9, 30, 0, 0, ist)
fmt.Println(istMeeting.UTC().Format(time.RFC3339))
}
UTC: 09:30 UTC
IST: 15:00 IST
2026-10-20T04:00:00Z
First, FixedZone creates the IST zone. Then In shows the same moment in that zone, and UTC converts back. In real apps, use time.LoadLocation("Asia/Kolkata"), which also knows daylight saving rules.
Program 13: Unix Timestamps
package main
import (
"fmt"
"time"
)
func main() {
newYear := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
// Unix gives the number of seconds since 1 January 1970 UTC.
fmt.Println(newYear.Unix())
// time.Unix goes the other way: seconds back into a time.
fmt.Println(time.Unix(0, 0).UTC())
fmt.Println(time.Unix(1767225600, 0).UTC().Format(time.DateOnly))
}
1767225600
1970-01-01 00:00:00 +0000 UTC
2026-01-01
A Unix timestamp counts seconds since 1 January 1970 UTC. Unix turns a time into that number, and time.Unix turns it back. Databases and APIs often store time this way.
Program 14: Truncate and Round to the Hour
package main
import (
"fmt"
"time"
)
func main() {
eventTime := time.Date(2026, 10, 20, 14, 47, 31, 0, time.UTC)
fmt.Println(eventTime.Truncate(time.Hour).Format(time.TimeOnly)) // always rounds down
fmt.Println(eventTime.Round(time.Hour).Format(time.TimeOnly)) // goes to the nearest hour
fmt.Println(eventTime.Truncate(15 * time.Minute).Format(time.TimeOnly)) // down to a 15-minute step
}
14:00:00
15:00:00
14:45:00
Truncate always goes down, and Round goes to the nearest step. Here 14:47 is closer to 15:00, so Round moves it up. This is useful for grouping events into hourly or 15-minute slots.
time.Time vs time.Duration in Go Date and Time Programs
In Go date and time programs, these two types are easy to mix up. The diagram and table below compare them.

| Feature | time.Time | time.Duration |
|---|---|---|
| Means | A moment, like 20 Oct 2026 09:30 | A length, like 90 minutes |
| Created with | time.Date, time.Now, time.Parse | time.Hour * 2, ParseDuration |
| Has a time zone | Yes | No |
| Add them together | Time + Duration with Add | Duration + Duration |
| Difference of two | t2.Sub(t1) gives a Duration | Simple subtraction |
So a Time answers “when”, and a Duration answers “how long”.
Common Mistakes in Go Date and Time Programs
- Using YYYY-MM-DD: Go needs the reference date, so write
2006-01-02. - Mixing up 01 and 02:
01is the month and02is the day, so02-01-2006is day-month-year. - Comparing with ==: two equal moments in different zones are not
==. UseEqual. - Storing local time: save times in UTC and convert to local only when you show them.
- Assuming every day has 24 hours: in zones with daylight saving, use
AddDatefor calendar days.
Best Practices for Go Date and Time Programs
- Use time.RFC3339 for APIs, JSON and logs.
- Keep times in UTC in databases and convert at the edges.
- Use constants like time.Hour instead of raw numbers of seconds.
- Pass the current time into functions like
age(birth, now), so tests can use fixed dates. - Check parse errors, because user dates are often wrong.
Go Date and Time Programs Interview Questions and Answers
Interviewers use short Go date and time programs to test the special rules of the time package. Each program is complete, with real output from Go 1.27.
Format and Parse Questions
Q1. Why does Go use 2006-01-02 15:04:05 for layouts?
It is a reference time where each part is a different number in order: 1 (month), 2 (day), 3 (hour), 4 (minute), 5 (second), 6 (year) and -7 (zone). So you write the layout as an example of the output you want.
Q2. What does this program print?
package main
import (
"fmt"
"time"
)
func main() {
moment := time.Date(2026, 3, 7, 5, 4, 9, 0, time.UTC)
fmt.Println(moment.Format("2-1-06 3:4:5")) // no leading zeros
fmt.Println(moment.Format("02-01-2006 03:04:05")) // leading zeros
}
7-3-26 5:4:9
07-03-2026 05:04:09
Without leading zeros, 2, 1, 3, 4 and 5 print single digits. Adding a 0 in front, as in 02, pads them to two digits. Also, 06 gives a two-digit year.
Q3. What does this program print?
package main
import (
"fmt"
"time"
)
func main() {
// The layout uses dashes, but the text uses slashes.
_, err := time.Parse("2006-01-02", "2026/10/20")
fmt.Println(err)
}
parsing time "2026/10/20" as "2006-01-02": cannot parse "/10/20" as "-"
The layout uses dashes, but the input uses slashes. The error message shows exactly where the shapes stop matching.
Duration and Maths Questions
Q4. What does this program print?
package main
import (
"fmt"
"time"
)
func main() {
januaryEnd := time.Date(2026, 1, 31, 0, 0, 0, 0, time.UTC)
fmt.Println(januaryEnd.AddDate(0, 1, 0).Format(time.DateOnly)) // add one month
}
2026-03-03
Adding one month to 31 January gives “31 February”, which does not exist. Go normalises it to 3 March in 2026. Handle month ends with care in billing code.
Q5. What does this program print?
package main
import (
"fmt"
"time"
)
func main() {
lesson := 90 * time.Minute
leftoverMinutes := int(lesson.Minutes()) % 60 // % gives the remainder
fmt.Println(lesson, lesson.Hours(), leftoverMinutes)
// 1500 times one millisecond is 1.5 seconds.
fmt.Println(time.Duration(1500) * time.Millisecond)
}
1h30m0s 1.5 30
1.5s
Ninety minutes prints as 1h30m0s, and Hours gives 1.5. The remainder of 90 divided by 60 is 30 leftover minutes. Go also picks the neatest unit when it prints a duration, such as 1.5s.
Q6. What is the zero value of time.Time?
package main
import (
"fmt"
"time"
)
func main() {
var emptyTime time.Time // declared but never set
fmt.Println(emptyTime)
fmt.Println(emptyTime.IsZero())
}
0001-01-01 00:00:00 +0000 UTC
true
It is the start of year 1 in UTC. Use IsZero to check whether a time was never set.
Comparison and Zone Questions for Go Date and Time Programs
Q7. What does this program print?
package main
import (
"fmt"
"time"
)
func main() {
ist := time.FixedZone("IST", 19800) // 19800 seconds is 5 hours 30 minutes
utcTime := time.Date(2026, 10, 20, 4, 0, 0, 0, time.UTC)
istTime := time.Date(2026, 10, 20, 9, 30, 0, 0, ist)
fmt.Println(utcTime == istTime, utcTime.Equal(istTime))
}
false true
Both values are the same moment, but they store different locations. == compares everything, while Equal compares only the moment. So always use Equal for times.
Q8. Why might time.LoadLocation fail?
It reads time zone data from the operating system. Small Docker images may not have that data, so the call returns an error. Import time/tzdata to embed the data in your binary.
Q9. What does this program print?
package main
import (
"fmt"
"time"
)
func main() {
date := time.Date(2026, 10, 18, 0, 0, 0, 0, time.UTC)
year, week := date.ISOWeek() // ISOWeek returns two values
fmt.Println(date.Weekday(), year, week)
}
Sunday 2026 42
ISOWeek gives the ISO 8601 week number, which many reports use. It returns the year and the week together.
Q10. How do you measure how long code takes?
Save start := time.Now() before the code, and call time.Since(start) after it. time.Now includes a monotonic clock reading, so the result stays correct even if the system clock changes.
Q11. What does this program print?
package main
import (
"fmt"
"slices"
"time"
)
// earlierFirst tells SortFunc how to order two dates.
func earlierFirst(first, second time.Time) int {
return first.Compare(second)
}
func main() {
dates := []time.Time{
time.Date(2026, 12, 1, 0, 0, 0, 0, time.UTC),
time.Date(2026, 3, 15, 0, 0, 0, 0, time.UTC),
time.Date(2026, 7, 4, 0, 0, 0, 0, time.UTC),
}
slices.SortFunc(dates, earlierFirst) // sorts the slice in place
for _, date := range dates {
fmt.Print(date.Format("Jan 2"), "; ")
}
fmt.Println()
}
Mar 15; Jul 4; Dec 1;
Time.Compare plugs straight into slices.SortFunc, as in our Go sorting programs. The helper returns a negative number when the first date is earlier.
Q12. What does this program print?
package main
import (
"fmt"
"time"
)
func main() {
for _, year := range []int{2024, 2026, 2100} {
// Try to build 29 February in this year.
feb29 := time.Date(year, 2, 29, 0, 0, 0, 0, time.UTC)
fmt.Println(year, feb29.Month() == time.February)
}
}
2024 true
2026 false
2100 false
This is a neat leap year check. If 29 February does not exist, time.Date moves it to 1 March, so the month is no longer February.
Practice Task
Subscriptions are a classic use of Go date and time programs. Write a program that takes a subscription start date and a plan length in months, then prints the end date and how many days are left from a fixed “today” date. Hint: use AddDate(0, months, 0) for the end date and Sub divided by 24 hours for days left.
Official Resources
Quick Recap
- Go date and time programs use
time.Timefor moments andtime.Durationfor lengths. - Layouts use the reference time
2006-01-02 15:04:05, not codes like YYYY. AddDatehandles calendar maths, whileAddandSubwork with durations.- Compare times with
Before,After,EqualorCompare, never with==. - Store times in UTC and convert with
InorLoadLocationwhen you show them.
What’s Next?
That completes Level 4 of our Go programs series. Coming soon: Level 5, starting with Go file programs that read, write and count lines in files. Until then, revise with the Go time package guide.


