Get Day, Month, and Year from Time in Go Language

huangapple go评论96阅读模式
英文:

Get Day, Month, and Year from Time in Go Language

问题

我有一个像这样的对象:

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

我想从fromDate和toDate中解析出日、月和年。我该如何做到这一点?是否有更好的类型可以使用,比如(Date),因为我不需要时间部分?

所以我想能够传递一个日期,像这样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的新手,谢谢你的帮助!

英文:

I have an object like this:

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

I want to be able to parse out the day, month, and year from the fromDate and the toDate. How can I do this? Is there a better type to use like (Date) because I do not need the time piece of it?

so I want to be able to pass a date like this 02/19/2016 and be able to get data.Day = 19, date.Month = 02, date.Year = 2016.

I was trying something like this:

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

This is an example of what I am currently using to create the searchObj:

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

I am new to Go and thank you for the help!

答案1

得分: 11

你所寻找的所有方法都存在于time.Time类型中。你可以这样做:

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

编辑:
我想使用time.Date可能更简洁,像这样:

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

All the methods you're looking for exist on the time.Time type. You can just do;

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

EDIT:
I suppose it would be more concise to use time.Date like so;

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

答案2

得分: 9

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

英文:

The time type also has Date() method which returns the year, month and day of the time in single call.

答案3

得分: 5

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

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

With the accepted method, if you need the month number you can simply cast the Month object to int since it's an enum:

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

huangapple
  • 本文由 发表于 2016年2月20日 06:17:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/35516120.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定