Go中time.RFC3339 时间格式化的实现
在开发过程中,我们有时会遇到这样的问题,将2020-11-08T08:18:46+08:00转成2020-11-0808:18:46,怎么解决这个问题?
解决这个问题,最好不要用字符串截取,或者说字符串截取是最笨的方法,这应该是时间格式化的问题。
我们先看一下golangtime包中支持的format格式:
const( ANSIC="MonJan_215:04:052006" UnixDate="MonJan_215:04:05MST2006" RubyDate="MonJan0215:04:05-07002006" RFC822="02Jan0615:04MST" RFC822Z="02Jan0615:04-0700"//RFC822withnumericzone RFC850="Monday,02-Jan-0615:04:05MST" RFC1123="Mon,02Jan200615:04:05MST" RFC1123Z="Mon,02Jan200615:04:05-0700"//RFC1123withnumericzone RFC3339="2006-01-02T15:04:05Z07:00" RFC3339Nano="2006-01-02T15:04:05.999999999Z07:00" Kitchen="3:04PM" //Handytimestamps. Stamp="Jan_215:04:05" StampMilli="Jan_215:04:05.000" StampMicro="Jan_215:04:05.000000" StampNano="Jan_215:04:05.000000000" )
我们找到了RFC3339,那就很简单了,我们封装一个方法RFC3339ToCSTLayout,见下面代码。
packagetimeutil import"time" var( cst*time.Location ) //CSTLayoutChinaStandardTimeLayout constCSTLayout="2006-01-0215:04:05" funcinit(){ varerrerror ifcst,err=time.LoadLocation("Asia/Shanghai");err!=nil{ panic(err) } } //RFC3339ToCSTLayoutconvertrfc3339valuetochinastandardtimelayout funcRFC3339ToCSTLayout(valuestring)(string,error){ ts,err:=time.Parse(time.RFC3339,value) iferr!=nil{ return"",err } returnts.In(cst).Format(CSTLayout),nil }
运行一下
RFC3339Str:="2020-11-08T08:18:46+08:00" cst,err:=timeutil.RFC3339ToCSTLayout(RFC3339Str) iferr!=nil{ fmt.Println(err) } fmt.Println(cst)
输出:
2020-11-0808:18:46
小结
同理,若遇到RFC3339Nano、RFC822、RFC1123等格式,也可以使用类似的方法,只需要在time.Parse()中指定时间格式即可。
到此这篇关于Go中time.RFC3339时间格式化的实现的文章就介绍到这了,更多相关Gotime.RFC3339时间格式化内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!