Library contents

Go time.Parse and Time.AddDate

time.Parse reads a date with Go's reference layout. AddDate advances calendar years, months, and days.

A simple example

time.Parse and Time.AddDate

  1. Start with 2024-01-31
  2. Do this Add one calendar day
  3. Result 2024-02-01
January ends on day 31. The next day starts a new month.

Syntax

Go syntax
day, err := time.Parse("2006-01-02", text)
Run this example in Go

Save the program as main.go. Use Go 1.21 or later.

go run main.go

Cross a leap day using a calendar date

A reporting or booking deadline falls close to the end of a month. Use a calendar operation and validate the input so a leap day or an invalid date cannot silently shift the deadline.

First output line2024-03-01
main.go
package main

import (
	"fmt"
	"time"
)

func main() {
	for _, text := range []string{"2024-02-29", "2023-02-29"} {
		day, err := time.Parse("2006-01-02", text)
		if err != nil {
			fmt.Println("invalid date")
			continue
		}
		fmt.Println(day.AddDate(0, 0, 1).Format("2006-01-02"))
	}
}
Output
2024-03-01
invalid date

The layout uses example digits from Go's reference date. Parsing rejects an impossible February 29, while adding one day to a valid leap day reaches March 1.

Go documentation for time.Parse and Time.AddDate

Advertisements

Return a borrowed microscope

A school lends a microscope two days before the end of February in a leap year. Parse the stated local calendar date and add the indicated number of days. Which date goes on the reminder?

Given28 February 2024 + 2 days
Worked result2024-03-01

Send a year-end reminder

A gallery schedules its reminder one day after the final day of the year. Parse the stated local calendar date and add the indicated number of days. Which date goes on the reminder?

Given31 December 2026 + 1 day
Worked result2027-01-01