Go Example: Time Formatting / Parsing

1. Introduction

Handling time is a common requirement in programming. In Go, the time package provides functionality for displaying and parsing dates and times. This blog post demonstrates how to format and parse time in Go using layout strings.

Definition

Time formatting in Go is based on a specific layout defined by the time package, which uses the reference time Mon Jan 2 15:04:05 MST 2006 to show the pattern with which to format and parse. Parsing time converts a string representation of the time into a time.Time object.

2. Program Steps

1. Import the time package.

2. Use the time.Now() function to get the current time.

3. Format the current time into different layouts.

4. Parse a time string into a time.Time object.

5. Handle any errors from parsing.

3. Code Program

package main

import (
	"fmt"
	"time"
)

func main() {
	// Step 2: Use time.Now() to get the current time
	now := time.Now()
	fmt.Println("Current time:", now)

	// Step 3: Format the current time
	fmt.Println("RFC1123 format:", now.Format(time.RFC1123))
	fmt.Println("Custom format (YYYY-MM-DD):", now.Format("2006-01-02"))

	// Step 4: Parse a time string into a time.Time object
	layout := "2006-01-02 15:04:05"
	timeStr := "2023-11-10 23:00:00"
	parsedTime, err := time.Parse(layout, timeStr)
	if err != nil {
		// Step 5: Handle errors from parsing
		fmt.Println("Error parsing time:", err)
	} else {
		fmt.Println("Parsed time:", parsedTime)
	}
}

Output:

Current time: 2023-04-12 15:04:05 +0000 UTC
RFC1123 format: Wed, 12 Apr 2023 15:04:05 UTC
Custom format (YYYY-MM-DD): 2023-04-12
Parsed time: 2023-11-10 23:00:00 +0000 UTC

Explanation:

1. The time package is imported for all time-related operations.

2. time.Now() is called to retrieve the current local time.

3. now.Format is used to convert the current time into strings with various formats. time.RFC1123 is a predefined layout constant. Custom layouts can be created using the reference time as a pattern.

4. time.Parse is used to convert a string into a time.Time object. The layout string must be created based on the reference time to define the format of the input string.

5. If time.Parse returns an error, it indicates the input string does not match the layout or contains invalid information, and the error is printed.

6. If there's no error, the parsed time is printed out in the standard format.

7. The output includes the current time, formatted time, and a parsed time from a string.


Comments