Golang : Calculate how many weeks left to go in a given year
Here is a simple tutorial on how to calculate the number of weeks in a given year and figure out how many more weeks left to go. A year can have either 52 or 53 weeks and care must be taken to properly get the last day of the last week in a year to get the correct number of weeks.
Here you go!
package main
import (
"fmt"
"time"
"github.com/jinzhu/now"
)
func main() {
tn := time.Now() // change this to calculate different year
fmt.Println("Now : ", tn.Format(time.ANSIC))
// this week is which number in the current calender year
_, currentWeekNumber := tn.ISOWeek()
fmt.Println("Current week number : ", currentWeekNumber)
// calculate the last week number for the current year
last := now.EndOfYear()
lastWeekOfTheYear := now.New(last).BeginningOfWeek()
fmt.Println("The day of the final week : ", lastWeekOfTheYear.Format(time.ANSIC))
_, lastWeekNumber := lastWeekOfTheYear.ISOWeek()
// verify at https://www.epochconverter.com/weeks/2019
fmt.Println("For the year", tn.Year(), ". It has", lastWeekNumber, "weeks.")
weeksLeft := lastWeekNumber - currentWeekNumber
fmt.Println("Hence, there are", weeksLeft, "weeks left to go.")
}
Output:
Now : Thu Jun 13 18:14:04 2019
Current week number : 24
The day of the final week : Sun Dec 29 00:00:00 2019
For the year 2019 . It has 52 weeks.
Hence, there are 28 weeks left to go.
Happy coding!
References :
https://www.socketloop.com/references/golang-time-time-isoweek-function-example
See also : Golang : Loop each day of the current month example
By Adam Ng(黃武俊)
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+18.9k Golang : When to use public and private identifier(variable) and how to make the identifier public or private?
+11.5k SSL : The certificate is not trusted because no issuer chain was provided
+6.2k Golang : How to search a list of records or data structures
+6.3k CodeIgniter : form input set_value cause " to become & quot
+5.8k Golang : Denco multiplexer example
+9.8k Golang : Translate language with language package example
+19.1k Golang : Check if directory exist and create if does not exist
+15.6k Golang : How to login and logout with JWT example
+7.5k Javascript : Push notifications to browser with Push.js
+9.6k Golang : Find correlation coefficient example
+15.2k nginx: [emerg] unknown directive "ssl"
+8.1k Golang : HttpRouter multiplexer routing example