BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu

Go by Example: Time Parsing

Go 1.23

Parsing time strings converts them into `time.Time` objects. This example demonstrates `time.Parse` and handling errors with different layouts.

Code

package main

import (
    "fmt"
    "time"
)

func main() {
    p := fmt.Println

    // 1. Basic Parsing (RFC3339)
    // Parse returns a time.Time and an error.
    t1, err := time.Parse(time.RFC3339, "2023-11-01T22:08:41+00:00")
    if err != nil {
        panic(err)
    }
    p("Parsed RFC3339:", t1)

    // 2. Custom Layout Parsing
    // The layout string must match the input format exactly.
    layout := "2006-01-02 3:04PM"
    str := "2023-10-31 8:00PM"
    
    t2, err := time.Parse(layout, str)
    if err != nil {
        panic(err)
    }
    p("Parsed Custom:", t2)

    // 3. ParseInLocation (Handling Timezones)
    // time.Parse usually returns time in UTC (if no offset is present).
    // Use ParseInLocation to interpret time in a specific zone.
    loc, _ := time.LoadLocation("America/New_York")
    t3, _ := time.ParseInLocation("2006-01-02", "2023-12-25", loc)
    p("Parsed in NY:", t3)

    // 4. Handling Errors
    _, err = time.Parse(time.RFC3339, "invalid-time")
    if err != nil {
        p("Parse Error:", err)
    }
}

Explanation

Parsing time in Go is the inverse operation of formatting, utilizing the same reference time layout system to interpret string representations of dates and times into native time.Time objects. The time.Parse function takes a layout string and an input string, attempting to match the input against the template; strict adherence to the layout is enforced, meaning that any deviation in separators, spacing, or component order will result in a parsing error. This strictness ensures data integrity but requires developers to be intimately familiar with the exact format of their input data, particularly when dealing with non-standard or legacy date strings.

A critical nuance in parsing is timezone handling: time.Parse interprets the input as UTC unless a timezone offset is explicitly present in the string. To parse a time string that lacks offset information but is known to represent a specific local time (e.g., "2023-01-01 12:00"), developers must use time.ParseInLocation, which accepts a *time.Location argument. This function correctly associates the parsed time with the specified timezone, handling daylight saving time transitions and offset calculations accurately, which is essential for building robust applications that operate across multiple geographic regions.

  • Strictness: Layout must match input exactly.
  • UTC Default: time.Parse defaults to UTC if no offset is found.
  • Locations: Use time.ParseInLocation for local times.
  • Errors: Always check the returned error object.

Code Breakdown

13
Parsing RFC3339. This is the safest way to exchange time data. The input string contains the date, time, and timezone offset (+00:00). 'time.Parse' reads this and creates a correct time object.
24
Parsing with a custom layout. We define the layout "2006-01-02 3:04PM" to match our input "2023-10-31 8:00PM". Since there is no timezone in the string, 't2' will be in UTC.
34
Using 'ParseInLocation'. We load the "America/New_York" location (timezone). Then we parse a date string. The resulting 't3' will have the correct offset for New York on that specific date (handling DST if applicable).
38
Error handling. If the input string doesn't match the layout (e.g., "invalid-time"), 'time.Parse' returns a non-nil error. Robust code must always handle this case.