• Documentation - https://pkg.go.dev/time
  • The time package provides functionality for working with time, dates, durations, and formatting.
import "time" 
  • Current Time - Get the current local time.
now := time.Now() // Returns time.Time  
  • Creating Specific Time
t := time.Date(  
	2024,  // year
	time.January, // month 
	10,  // day
	15,  // hour
	30,  // minutes
	0,  // seconds
	0,  // nanoseconds
	time.UTC,  // location
)  
  • Time Parsing (String → time) - Convert a string into time.Time using Parse.
    • Go uses a reference time layout => Mon Jan 2 15:04:05 MST 2006
date := "Tue, 09/22/1995, 13:00"  
layout := "Mon, 01/02/2006, 15:04"  
  
t, err := time.Parse(layout, date)  
  • Time Formatting (time → String) - Convert time.Time to a string.
t := time.Now()  
  
formatted := t.Format("2006-01-02 15:04:05")  
  • Comparing Times
t1.After(t2)  // true if `t1` is after `t2`
t1.Before(t2)  // true if `t1` is before `t2`
t1.Equal(t2) // Checks if both times are equal
  • Time Duration - Duration represents the elapsed time between two instants.
duration := time.Hour  
duration := 30 * time.Minute  
  • Common durations

    ConstantMeaning
    time.Nanosecond1 nanosecond
    time.Microsecond1 microsecond
    time.Millisecond1 millisecond
    time.Second1 second
    time.Minute1 minute
    time.Hour1 hour
  • Measuring Execution Time

start := time.Now()  
  
// code execution  
  
elapsed := time.Since(start)   // Performance measurement
  • Adding or Subtracting Time
t := time.Now()  
future := t.Add(2 * time.Hour)  
 
diff := t1.Sub(t2) // Returns time.Duration
  • Unix Time - Unix timestamp represents seconds since Jan 1, 1970 (UTC).
t := time.Now()  
ts := t.Unix() // Get Unix time
 
t := time.Unix(1700000000, 0) // Create time from unix