Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

date

datetime

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!

like image 578
user3788671 Avatar asked Feb 19 '16 22:02

user3788671


3 Answers

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()
like image 156
evanmcdonnal Avatar answered Sep 30 '22 17:09

evanmcdonnal


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

like image 27
ain Avatar answered Sep 30 '22 18:09

ain


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)
like image 33
miqrc Avatar answered Sep 30 '22 16:09

miqrc