如何将日期转换为不同的格式?

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

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")

这里有一个用于测试的Playground

英文:

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")

A playground to test with.

答案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
}

huangapple
  • 本文由 发表于 2016年4月23日 14:43:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/36807596.html
匿名

发表评论

匿名网友

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

确定