Home > database >  Date format in Go
Date format in Go

Time:01-24

I need to format a Date.Time object which is a UTC string into the following format “dd/mm/yyyy HH:MM:SS”. I need to loop through an array of transactions and alter the StatusDateTime for each transaction in the array.

I've tried the below while playing around with the format, but it does not alter the date format at all.

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

What am I doing wrong?

CodePudding user response:

There's a bit of confusion in this question. Let me break it down.

I need to format a Date.Time object which is a UTC string into the following format “dd/mm/yyyy HH:MM:SS”.

First, I think you mean a time.Time object. There's no such thing as a Date.Time object in Go.

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

Now, you're on the right track by calling the Format method of time.Time. But as you can see by reading the Godoc for that method, it returns a string. Your code example ignores (and therefore discards) that return value.

You need to assign that value somewhere, 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've tried the below while playing around with the format, but it does not alter the date format at all.

Not to beat a dead horse here, but you're right, this doesn't alter the format at all... Or more accurately, time.Time has no format to alter in the first place.

  • Related