Skip to content

Date & Time

Compare Time

go
    today := time.Now()
    tomorrow := today.Add(24 * time.Hour)
  
    // Using time.Before() method
    g1 := today.Before(tomorrow)
    fmt.Println("today before tomorrow:", g1) 
    
    // Using time.After() method
    g2 := tomorrow.After(today)
    fmt.Println("tomorrow after today:", g2)
go
      // calculate total number of days
	duration := time.Now().Sub(start)
	fmt.Printf("difference %d days", int(duration.Hours()/24) )

Duration

go
// Common durations. There is no definition for units of Day or larger
// to avoid confusion across daylight savings time zone transitions.
//
// To count the number of units in a Duration, divide:
//
//	second := time.Second
//	fmt.Print(int64(second/time.Millisecond)) // prints 1000
//
// To convert an integer number of units to a Duration, multiply:
//
//	seconds := 10
//	fmt.Print(time.Duration(seconds)*time.Second) // prints 10s
const (
	Nanosecond  Duration = 1
	Microsecond          = 1000 * Nanosecond
	Millisecond          = 1000 * Microsecond
	Second               = 1000 * Millisecond
	Minute               = 60 * Second
	Hour                 = 60 * Minute
)
go
t := time.Now().Add(time.Hour * 24 * 7)

Create Date

go
t := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
t1 := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, t.Nanosecond(), t.Location())

Edit Date

go
func (t Time) AddDate(years int, months int, days int) Time
func (t Time) Add(d Duration) Time

after := now.AddDate(1, 0, 0)
fmt.Println("\nAdd 1 Year:", after)
after = now.Add(10*time.Microsecond)
fmt.Println("\nAdd 10 Microsecond:", after)

Epoc Unix Time Stamp

go
time.Now().Unix()

Parse and Format Date String

Layout

Mon Jan 2 15:04:05 MST 2006  (MST is GMT-0700)
01/02 03:04:05PM '06 -0700

Parse Date String

go
package main

import (
    "fmt"
    "time"
)

func main() {
    value  := "Thu, 05/19/11, 10:47PM"
    // Writing down the way the standard time would look like formatted our way
    layout := "Mon, 01/02/06, 03:04PM"
    t, _ := time.Parse(layout, value)
    fmt.Println(t)
}

// => "Thu May 19 22:47:00 +0000 2011"
go
layout := "2006-01-02"
loc, err := time.LoadLocation("EST")
if err != nil {
		return nil, fmt.Errorf("load EST location:%w", err)
}
dateTime, err := time.ParseInLocation(format, dateStr, loc)
if err != nil {
	return trades, fmt.Errorf("index:%d parse date:%w", i, err)
}

2020-08-08T00:22:44Z would be a valid RFC3339 date

go
    t, err := time.Parse(time.RFC3339, "2020-08-08T00:22:44Z")
    if err != nil {
        panic(err)
    }
    fmt.Println(t) // 2020-08-08 00:22:44 +0000 UTC

Format to Date String

go
package main

import (
    "fmt"
    "time"
)

func main() {
    t := time.SecondsToLocalTime(1305861602)
    t.ZoneOffset = -4*60*60
    fmt.Println(t.Format("2006-01-02 15:04:05 -0700"))
}

// => "2011-05-20 03:20:02 -0400

References