How to format a date using different formats in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "time"
)

func main() {
    // Current time
    var now time.Time = time.Now()

    fmt.Println("Original time:", now, "\n")

    // --- BASIC FORMATS ---

    fmt.Println("Year:", now.Format("2006"))                
    fmt.Println("Month (01-12):", now.Format("01"))         
    fmt.Println("Day:", now.Format("02"))                  
    fmt.Println("Hour (24h):", now.Format("15"))           
    fmt.Println("Minute:", now.Format("04"))                
    fmt.Println("Second:", now.Format("05"))                

    // --- COMMON FULL FORMATS ---

    fmt.Println("YYYY-MM-DD:", now.Format("2006-01-02"))
    fmt.Println("DD/MM/YYYY:", now.Format("02/01/2006"))
    fmt.Println("MM-DD-YYYY:", now.Format("01-02-2006"))
    fmt.Println("YYYY/MM/DD HH:MM:SS:", now.Format("2006/01/02 15:04:05"))

    // --- TIME FORMATS ---

    fmt.Println("24-hour time:", now.Format("15:04:05"))
    fmt.Println("12-hour time:", now.Format("03:04:05 PM"))

    // --- TEXTUAL MONTHS & WEEKDAYS ---

    fmt.Println("Month name (short):", now.Format("Jan"))    
    fmt.Println("Month name (full):", now.Format("January")) 
    fmt.Println("Weekday (short):", now.Format("Mon"))       
    fmt.Println("Weekday (full):", now.Format("Monday"))    

    // --- FULL HUMAN-READABLE FORMATS ---

    fmt.Println("Full date:", now.Format("Monday, January 2, 2006"))
    fmt.Println("Full date + time:", now.Format("Monday, January 2, 2006 15:04:05"))

    // --- RFC / ISO STANDARDS ---

    fmt.Println("RFC1123:", now.Format(time.RFC1123))
    fmt.Println("RFC3339:", now.Format(time.RFC3339))
    fmt.Println("ISO8601-like:", now.Format("2006-01-02T15:04:05Z07:00"))

    // --- CUSTOM FORMAT WITH TIMEZONE ---

    fmt.Println("With timezone:", now.Format("2006-01-02 15:04:05 MST"))
}



/*
run:

Original time: 2026-05-20 15:44:25.984604531 +0000 UTC m=+0.000041972 

Year: 2026
Month (01-12): 05
Day: 20
Hour (24h): 15
Minute: 44
Second: 25
YYYY-MM-DD: 2026-05-20
DD/MM/YYYY: 20/05/2026
MM-DD-YYYY: 05-20-2026
YYYY/MM/DD HH:MM:SS: 2026/05/20 15:44:25
24-hour time: 15:44:25
12-hour time: 03:44:25 PM
Month name (short): May
Month name (full): May
Weekday (short): Wed
Weekday (full): Wednesday
Full date: Wednesday, May 20, 2026
Full date + time: Wednesday, May 20, 2026 15:44:25
RFC1123: Wed, 20 May 2026 15:44:25 UTC
RFC3339: 2026-05-20T15:44:25Z
ISO8601-like: 2026-05-20T15:44:25Z
With timezone: 2026-05-20 15:44:25 UTC

*/

 



answered May 20 by avibootz
...