问题描述
我想将字符串"20101011"
转换为有效日期(2010-10-11
),但无法确定我们该怎么做.
I want to convert a string "20101011"
to a valid date (2010-10-11
), but could not figure our how to do it.
我尝试过:
now := time.Now()
date := now.Format("20101011")
和
date, _ := time.Parse("20101011", "20101011")
都没有工作.
推荐答案
import "time"
const (
ANSIC = "Mon Jan _2 15:04:05 2006"
UnixDate = "Mon Jan _2 15:04:05 MST 2006"
RubyDate = "Mon Jan 02 15:04:05 -0700 2006"
RFC822 = "02 Jan 06 15:04 MST"
RFC822Z = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
RFC850 = "Monday, 02-Jan-06 15:04:05 MST"
RFC1123 = "Mon, 02 Jan 2006 15:04:05 MST"
RFC1123Z = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone
RFC3339 = "2006-01-02T15:04:05Z07:00"
RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
Kitchen = "3:04PM"
// Handy time stamps.
Stamp = "Jan _2 15:04:05"
StampMilli = "Jan _2 15:04:05.000"
StampMicro = "Jan _2 15:04:05.000000"
StampNano = "Jan _2 15:04:05.000000000"
)
这些是预定义的布局,用于Time.Format和Time.Parse. 布局中使用的参考时间是特定时间:
These are predefined layouts for use in Time.Format and Time.Parse. The reference time used in the layouts is the specific time:
Mon Jan 2 15:04:05 MST 2006
,这是Unix时间1136239445.由于MST是GMT-0700,因此参考 时间可以认为是
which is Unix time 1136239445. Since MST is GMT-0700, the reference time can be thought of as
01/02 03:04:05PM '06 -0700
要定义自己的格式,请写下参考时间 看起来像格式化了您的方式;查看诸如ANSIC之类的常量的值, 例如,StampMicro或Kitchen.该模型是为了演示 参考时间看起来像这样,以便Format和Parse方法可以 将相同的转换应用于一般时间值.
To define your own format, write down what the reference time would look like formatted your way; see the values of constants like ANSIC, StampMicro or Kitchen for examples. The model is to demonstrate what the reference time looks like so that the Format and Parse methods can apply the same transformation to a general time value.
将time
格式字符串"20060102"
用于YYYYMMDD
.将time
格式字符串"2006-01-02"
用于YYYY-MM-DD
.
Use the time
format string "20060102"
for YYYYMMDD
. Use the time
format string "2006-01-02"
for YYYY-MM-DD
.
例如,
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
fmt.Println(now)
date := now.Format("20060102")
fmt.Println(date)
date = now.Format("2006-01-02")
fmt.Println(date)
date2, err := time.Parse("20060102", "20101011")
if err == nil {
fmt.Println(date2)
}
}
输出:
2009-11-10 23:00:00 +0000 UTC
20091110
2009-11-10
2010-10-11 00:00:00 +0000 UTC
这篇关于在Go中将YYYYMMDD字符串转换为有效日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!