Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Date format in Golang

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading