Go中的日期格式化

huangapple go评论82阅读模式
英文:

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.TimeFormat 方法是正确的。但是,通过阅读该方法的 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.

huangapple
  • 本文由 发表于 2023年1月24日 18:25:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75220152.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定