【问题标题】:Get Day, Month, and Year from Time in Go Language在 Go 语言中从时间获取日、月和年
【发布时间】:2016-02-19 22:17:43
【问题描述】:

我有一个这样的对象:

type searchObj struct {
    symbol string
    dataType string
    fromDate time.Time
    toDate time.Time
}

我希望能够从 fromDate 和 toDate 中解析出日、月和年。我怎样才能做到这一点?有没有更好的类型可以使用(日期),因为我不需要它的时间片段?

所以我希望能够传递这样的日期 02/19/2016 并能够获取 data.Day = 19, date.Month = 02, date.Year = 2016。

我正在尝试这样的事情:

search.fromDate.Date.Month
search.fromDate.Date.Day
search.fromDate.Date.Year

这是我目前用于创建 searchObj 的示例:

time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)

我是 Go 新手,感谢您的帮助!

【问题讨论】:

  • time.Time 上的 Month()、Day() 和 Year() 方法怎么样?
  • @JimB:那很贵。使用func (Time) Date
  • @peterSO,是的,我自己没有检查文档;)

标签: date datetime go


【解决方案1】:

您要查找的所有方法都存在于 time.Time 类型上。你可以这样做;

year := fromDate.Year()
month := fromDate.Month()
day := fromDate.Day()

编辑: 我想这样使用 time.Date 会更简洁;

year, month, day := fromDate.Date()

【讨论】:

  • 这就是我要找的。谢谢,很抱歉提出了不好的问题。
  • @user3788671 那是 nbd。对于熟悉包/类型的人来说可能很明显,但如果它不在 SO 上,那么询问它是有价值的。
【解决方案2】:

time 类型还有Date() 方法,它在一次调用中返回时间的年、月和日。

【讨论】:

    【解决方案3】:

    使用接受的方法,如果您需要月份 number,您可以简单地将 Month 对象转换为 int,因为它是一个枚举:

    year, month, day := time.Now().Date()
    log.Printf("%v-%v-%v", year, int(month), day)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-26
      • 2012-03-17
      • 2016-07-27
      • 1970-01-01
      • 1970-01-01
      • 2010-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多