Home >Backend Development >Golang >Date format in Go

Date format in Go

WBOY
WBOYforward
2024-02-15 15:42:08767browse

Go 中的日期格式

php editor Strawberry will introduce to you the date format in Go language today. In the Go language, date and time processing is very important, and date formatting is one of the operations we often need to perform. The Go language provides a simple and powerful date formatting method that can meet our various needs. Whether it is converting a date to a string or parsing a string into a date, the Go language provides corresponding functions and methods to perform operations. Next, let us learn about the date format in Go language!

Question content

I need to format a date.time object (utc string) into the following format "dd/mm/yyyy hh:mm:ss". I need to loop through an array of transactions and change the statusdatetime of each transaction in the array.

I tried the following while trying the format but it doesn't change the date format at all.

for _, Transaction := range Transactions {
        Transaction.StatusDateTime.Format("2006-01-02T15:04:05")
    }

What did i do wrong?

Solution

This problem is a bit confusing. Let me break it down.

I need to format a date.time object (utc string) into the following format "dd/mm/yyyy hh:mm:ss".

First of all, I think you mean a time.time object. There is no such thing as a date.time object in go.

Second, the time.time object is an object (a struct instance, anyway). It is not a "utc string". It's not a rope at all! It is an arbitrary value stored in memory.

Now, by calling the format method of time.time, you are on the right track. But as you can see by reading the godoc of the method, it returns a string. Your code example ignores (and therefore discards) that return value.

You need to assign that value somewhere and then presumably do something with it:

for _, Transaction := range Transactions {
    formatted := Transaction.StatusDateTime.Format("2006-01-02T15:04:05")
    fmt.Println("the formatted time is", formatted)
    /* Or store the formatted time somewhere, etc */
}

I tried the following while trying the format but it doesn't change the date format at all.

Not to beat a dead horse here, but you're right, this doesn't change the format at all...or more accurately, time.time There's nothing to change FormatFirst place.

The above is the detailed content of Date format in Go. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete