英文:
Date format in Go
问题
我需要将一个UTC字符串表示的Date.Time对象格式化为“dd/mm/yyyy HH:MM:SS”的格式。我需要遍历一个交易数组,并修改数组中每个交易的StatusDateTime。
我尝试了下面的代码,但它并没有改变日期格式:
for _, Transaction := range Transactions {
Transaction.StatusDateTime.Format("2006-01-02T15:04:05")
}
我做错了什么?
英文:
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?
答案1
得分: 3
这个问题有点混乱。让我来解释一下。
首先,我认为你指的是一个 time.Time
对象。Go 中没有 Date.Time
对象。
其次,time.Time
对象实际上是一个对象(或者说是一个结构体实例),它不是一个“UTC字符串”。它根本不是一个字符串!它是存储在内存中的任意值。
现在,你通过调用 time.Time
的 Format
方法是正确的。但是,通过阅读该方法的 Godoc,你会发现它返回一个字符串。你的代码示例忽略了(因此丢弃了)该返回值。
你需要将该值赋给某个变量,然后可能要对其进行一些操作:
for _, Transaction := range Transactions {
formatted := Transaction.StatusDateTime.Format("2006-01-02T15:04:05")
fmt.Println("the formatted time is", formatted)
/* 或者将格式化后的时间存储在某个地方等等 */
}
另外,你尝试了下面的代码,但它并没有改变日期格式。
不想再多说废话了,但你是对的,这并没有改变日期格式... 更准确地说,time.Time
本身根本没有日期格式需要改变。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论