英文:
How to convert date to different formats?
问题
我想将日期格式从2010-01-23 11:44:20
转换为Jan 23 '10 at 11:44
,使用Go语言。我尝试了time包中的几个函数,但没有成功。
有人可以帮我解决这个问题吗?
英文:
I would like to convert date format from 2010-01-23 11:44:20
to Jan 23 '10 at 11:44
in Go. I tried few functions from time package but couldn't make it.
Could someone help me with this?
答案1
得分: 8
你可以使用time包的Parse和Format函数将其转换为所需的文本格式。这两个函数都需要一个参考时间(2006-01-02 15:04:05)作为参数,该参考时间的格式可以很容易理解。
dtstr1 := "2010-01-23 11:44:20"
dt, _ := time.Parse("2006-01-02 15:04:05", dtstr1)
dtstr2 := dt.Format("Jan 2 '06 at 15:04")
英文:
You could use the time package's Parse
and Format
to convert it to the desired text format. Both take a reference time (2006-01-02 15:04:05) in the format you require as a parameter which makes the format fairly easy to understand.
dtstr1 := "2010-01-23 11:44:20"
dt,_ := time.Parse("2006-01-02 15:04:05", dtstr1)
dtstr2 := dt.Format("Jan 2 '06 at 15:04")
答案2
得分: 1
一种方法是使用time包的Parse和Format函数,
另一种方法是编写自己的格式化函数,如下所示:
package main
import (
"bytes"
"fmt"
"time"
)
// 将时间格式从"2010-01-23 11:44:20"转换为"Jan 23 '10 at 11:44"
func FormatDateTime(t time.Time) string {
var buffer bytes.Buffer
buffer.WriteString(t.Month().String()[:3])
buffer.WriteString(fmt.Sprintf(" %2d '%2d at %2d:%2d", t.Day(), t.Year()%100, t.Hour(), t.Minute()))
return buffer.String()
}
func main() {
t := time.Now()
str := FormatDateTime(t)
fmt.Println(str) // 输出:Apr 23 '16 at 11:50
}
英文:
One way is to use the time package's Parse and Format functions,
or another way is to write your own formatter function like this:
package main
import (
"bytes"
"fmt"
"time"
)
//2010-01-23 11:44:20 to Jan 23 '10 at 11:44
func FormatDateTime(t time.Time) string {
var buffer bytes.Buffer
buffer.WriteString(t.Month().String()[:3])
buffer.WriteString(fmt.Sprintf(" %2d '%2d at %2d:%2d", t.Day(), t.Year()%100, t.Hour(), t.Minute()))
return buffer.String()
}
func main() {
t := time.Now()
str := FormatDateTime(t)
fmt.Println(str) //Apr 23 '16 at 11:50
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论