In this article, we will see how to change the DateTime format in Golang using the time
package. We also see how to parse and format the DateTime values.
Parsing:
You must first parse the date string into a time.Time value in order to work with DateTime values in Golang. The time package includes the time.Parse function, which requires the layout and the date string to be parsed as two string arguments. The layout, which is a string, specifies how the date string should be formatted.
Here’s an example of how to parse a date string:
package main
import (
"fmt"
"time"
)
func main() {
layout := "2006-01-02 15:04:05"
dateString := "2023-03-23 18:30:45"
t, err := time.Parse(layout, dateString)
if err != nil {
fmt.Println("Error parsing date string:", err)
} else {
fmt.Println("Parsed time:", t)
}
}
In the above example, we define a layout using the format “2006-01-02 15:04:05” and a date string to be parsed. time.Time value is returned, If the date string matches the layout.
Formatting:
After parsing a DateTime value, you can change its format using the time.Time.Format
method. It takes a format string as its argument and returns a formatted date string.
package main
import (
"fmt"
"time"
)
func main() {
layout := "2006-01-02 15:04:05"
dateString := "2023-03-23 18:30:45"
t, err := time.Parse(layout, dateString)
if err != nil {
fmt.Println("Error parsing date string:", err)
return
}
newLayout := "02-Jan-2006 03:04 PM"
formattedTime := t.Format(newLayout)
fmt.Println("Formatted time:", formattedTime)
}
In the above example, we first parse a date string into a time.Time
value, then change its format using the Format
method with a new layout. The new layout in this example is “02-Jan-2006 03:04 PM“, which displays the day, month name, year, hour, minute, and AM/PM indicator.
As we already know how to parse and format the datetime, we can easily change the format of a given datetime string by first parsing it into a time.Time
value and then formatting it into the desired format.
Here’s an example of how to change the datetime format:
package main
import (
"fmt"
"time"
)
func changeDateTimeFormat(input string, inputLayout string, outputLayout string) (string, error) {
t, err := time.Parse(inputLayout, input)
if err != nil {
return "", err
}
return t.Format(outputLayout), nil
}
func main() {
input := "2023-03-23T19:00:00Z"
inputLayout := "2006-01-02T15:04:05Z"
outputLayout := "02-01-2006 15:04:05"
output, err := changeDateTimeFormat(input, inputLayout, outputLayout)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Original:", input)
fmt.Println("Changed format:", output)
}
In the above example, we define a function called changeDateTimeFormat
that takes an input datetime string, an input layout string, and an output layout string.
The function first parses the input datetime string into a time.Time
value using the input layout string and then formats it into the desired output format using the output layout string.