How to get last date of the given year?

How can I get the last date of the year? I am trying to create a function where I give year in int like 2020 which returns me the last date of the year which will be 31-Dec-2020.

Can someone plz tell me how I can do it?

2 Likes

Is something like this what you are looking for?

https://play.golang.org/p/Fw2QBjCUqXl

1 Like

Yes, thank you so much.

1 Like

No problem!

Gregorian dates do not obey the normal rules of arithmetic. There are different numbers of days in a month. There are different numbers of days in February in leap and non-leap years.

Do not hard code dates (like 12 and 31) unnecessarily. Let the Go time package do the work.

func Date

func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time

Date returns the Time corresponding to

yyyy-mm-dd hh:mm:ss + nsec nanoseconds

in the appropriate zone for that time in the given location.

The month, day, hour, min, sec, and nsec values may be outside their usual ranges and will be normalized during the conversion. For example, October 32 converts to November 1.

Write the code for the complex case, lastDateOfMonth, using normalization: day 0 is the last day of the previous month. Then use the same principles for lastDateOfYear.

package main

import (
	"fmt"
	"time"
)

func lastDateOfYear(year int) time.Time {
	return time.Date(year+1, 1, 0, 0, 0, 0, 0, time.UTC)
}

func lastDateOfMonth(year int, month time.Month) time.Time {
	return time.Date(year, month+1, 0, 0, 0, 0, 0, time.UTC)
}

func main() {
	for y := 2019; y <= 2021; y++ {
		fmt.Println(lastDateOfYear(y))
	}
	fmt.Println()
	for y, m := 2020, time.Month(1); m <= 12; m++ {
		fmt.Println(lastDateOfMonth(y, m))
	}
	for y, m := 2021, time.Month(1); m <= 3; m++ {
		fmt.Println(lastDateOfMonth(y, m))
	}
}
2019-12-31 00:00:00 +0000 UTC
2020-12-31 00:00:00 +0000 UTC
2021-12-31 00:00:00 +0000 UTC

2020-01-31 00:00:00 +0000 UTC
2020-02-29 00:00:00 +0000 UTC
2020-03-31 00:00:00 +0000 UTC
2020-04-30 00:00:00 +0000 UTC
2020-05-31 00:00:00 +0000 UTC
2020-06-30 00:00:00 +0000 UTC
2020-07-31 00:00:00 +0000 UTC
2020-08-31 00:00:00 +0000 UTC
2020-09-30 00:00:00 +0000 UTC
2020-10-31 00:00:00 +0000 UTC
2020-11-30 00:00:00 +0000 UTC
2020-12-31 00:00:00 +0000 UTC
2021-01-31 00:00:00 +0000 UTC
2021-02-28 00:00:00 +0000 UTC
2021-03-31 00:00:00 +0000 UTC
3 Likes

Thanks! Iā€™m going to do it this way next time I need to do something like this!

Good to keep this in mind when dealing with more complex situations than just the last day of the year.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.