Home > Backend Development > Golang > How Can I Convert Dates to Different Formats Using Go's `time` Package?

How Can I Convert Dates to Different Formats Using Go's `time` Package?

DDD
Release: 2024-12-21 17:39:09
Original
351 people have browsed it

How Can I Convert Dates to Different Formats Using Go's `time` Package?

Converting Dates to Various Formats in Go

Converting dates between different formats, such as changing "2010-01-23 11:44:20" to "Jan 23 '10 at 11:44," can be achieved using Go's time package.

To accomplish this, leverage the Parse and Format functions provided by the time package. These functions require a reference time in the desired format as a parameter. This format parameter defines the layout of the desired output.

For example, to convert the date "2010-01-23 11:44:20" to "Jan 23 '10 at 11:44" in Go:

package main

import (
    "fmt"
    "time"
)

func main() {
    dtstr1 := "2010-01-23 11:44:20"
    dt, _ := time.Parse("2006-01-02 15:04:05", dtstr1)

    dtstr2 := dt.Format("Jan 2 '06 at 15:04")

    fmt.Println(dtstr2) // Output: Jan 23 '10 at 15:04
}
Copy after login

The Parse function takes the reference time format "2006-01-02 15:04:05" and the input date string "2010-01-23 11:44:20" as parameters, and returns a time.Time object representing the parsed date.

The Format function then takes the time.Time object and the reference time format "Jan 2 '06 at 15:04" as parameters, and returns the converted date string "Jan 23 '10 at 11:44."

This approach allows for easy conversion of dates between a wide range of formats by specifying the desired reference time format parameters.

The above is the detailed content of How Can I Convert Dates to Different Formats Using Go's `time` Package?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template