Home >Backend Development >Golang >How to Convert Date Formats in Go Using `time.Parse` and `time.Format`?

How to Convert Date Formats in Go Using `time.Parse` and `time.Format`?

Susan Sarandon
Susan SarandonOriginal
2024-12-12 10:29:15310browse

How to Convert Date Formats in Go Using `time.Parse` and `time.Format`?

Date Format Conversion in Go

In the realm of Go programming, the conversion of date formats is a common task. One may encounter the need to transform dates from one format to another, such as converting "2010-01-23 11:44:20" to "Jan 23 '10 at 11:44."

To achieve this conversion, leverage the time package's Parse and Format functions.

Using Parse and Format

The Parse function takes a reference time (e.g., "2006-01-02 15:04:05") and a date string in the format you want to convert from. This format acts as a template to decode the input string into a time.Time object.

The Format function does the opposite. It takes a time.Time object and a reference time as parameters and returns a string representing the time in the specified format.

Example Code

Below is an example code to convert the date string "2010-01-23 11:44:20" to "Jan 23 '10 at 11:44":

package main

import (
    "fmt"
    "time"
)

func main() {
    dtstr1 := "2010-01-23 11:44:20"
    dt, err := time.Parse("2006-01-02 15:04:05", dtstr1)
    if err == nil {
        dtstr2 := dt.Format("Jan 2 '06 at 15:04")
        fmt.Println(dtstr2) // Output: Jan 23 '10 at 11:44
    } else {
        fmt.Println(err)
    }
}

This code will print the converted date string "Jan 23 '10 at 11:44" to the console.

The above is the detailed content of How to Convert Date Formats in Go Using `time.Parse` and `time.Format`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn