dongyan2267 2015-11-18 23:30
浏览 741

在Go中将YYYYMMDD字符串转换为有效日期

I want to convert a string "20101011" to a valid date (2010-10-11), but could not figure our how to do it.

I tried:

now := time.Now()
date := now.Format("20101011")

and

date, _ := time.Parse("20101011", "20101011")

neither one worked.

  • 写回答

1条回答 默认 最新

  • dongrou839975 2015-11-19 00:08
    关注

    Package time

    import "time" 
    

    Constants

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

    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

    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
    

    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.

    Use the time format string "20060102" for YYYYMMDD. Use the time format string "2006-01-02" for YYYY-MM-DD.

    For example,

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

    Output:

    2009-11-10 23:00:00 +0000 UTC
    20091110
    2009-11-10
    2010-10-11 00:00:00 +0000 UTC
    
    评论

报告相同问题?

悬赏问题

  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题