【问题标题】:How to convert time.Time object to formatted string using .Format in golang?如何在 golang 中使用 .Format 将 time.Time 对象转换为格式化字符串?
【发布时间】:2016-11-21 16:32:15
【问题描述】:

我目前正在尝试从我的 SQL 数据库中获取 time.Time 对象并将检索到的值转换为如下所示的格式化字符串:

TIME_FORMAT := "%Y-%m-%dT%H:%M:%S"

这是我在 Python 中用来做同样事情的格式,但我知道它不适合 go。我已经从数据库中获取了值,现在只需要格式化它。请注意,我已将 ccc.Ia_date 定义为 interface{} 类型,因为数据库中的此值可能为空。这是我的代码片段:

fmt.Println(reflect.TypeOf(ccc.Ia_date))  //gives me time.Time
t := ccc.Ia_date //which prints as: 2016-11-16 21:06:39 +0000 +0000
fmt.Println(t.Format())

我收到以下错误:

t.Format undefined (type interface {} 是没有方法的接口)

我错过了导入吗?或者这只是不可能使用接口类型?如果是这样,我必须接受来自数据库的空值的替代方案是什么? (我已经看到Golang: convert time.Time to string 的相关答案 - 我尝试了该解决方案,但我没有抓住时间。现在,这是我看到的唯一区别)

【问题讨论】:

    标签: postgresql go interface formatting


    【解决方案1】:

    如果你有一个interface{} 值持有一个time.time 值,你可以使用type assertion 来获取包装的time.Time

    if t, ok := ccc.Ia_date.(time.Time); ok {
        // here t is of type time.Time, and so you can call its Format() method:
        fmt.Println(t.Format(layout))
    } else {
        // ccc.Ia_date is not of type time.Time, or it is nil
    }
    

    请注意,如果您想允许nil,则只使用指针*time.Time 会更容易,因此您不需要使用类型断言。有关详细信息,请参阅此答案:Golang JSON omitempty With time.Time Field

    如果ccc.Ia_date 的类型为*time.Time

    if ccc.Ia_date != nil {
        fmt.Println(ccc.Ia_date.Format(layout))
    }
    

    你想要的格式的布局字符串是:

    layout := "2006-01-02T15:04:05"
    

    【讨论】:

    • 感谢您的快速回复。问题是,如果我在一个结构(我所做的 --> ccc.Ia_date)中将 Ia_date 定义为 *time.Time,我无法将新转换的字符串分配回该值,因为它只接受 *time 类型的对象。有时间我试试你的界面解决方案。
    【解决方案2】:

    您有多个问题。首先,如果ccc.Ia_dateinterface{},则必须先将其类型断言为time.Time,然后才能使用time.Time 的任何方法。您可以使用双参数类型断言形式来避免恐慌:

    t, ok := ccc.Ia_date.(time.Time)
    if !ok {
        // wrong type or nil value, handle it
    }
    t.Format(timeFormat)
    

    您还需要定义格式字符串。格式字符串定义为标准化的日期和时间,即Mon Jan 2 15:04:05 -0700 MST 2006。所以对于你的格式,你想要:

    time_format := "2006-01-02T15:04:05"
    t.Format(timeFormat)
    

    但是,这缺少时区。它也几乎与 RFC3339 ("2006-01-02T15:04:05Z07:00") 相同,您可以使用它来代替:

    t.Format(time.RFC3339)
    

    【讨论】:

      猜你喜欢
      • 2016-01-12
      • 1970-01-01
      • 2022-10-01
      • 2017-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-22
      • 2022-11-14
      相关资源
      最近更新 更多