Golang : Loop each day of the current month example
Problem:
You need to get the current month, find out the number of days in the month programmatically and loop through each day to perform certain tasks such as restoring archived data from backups or interpolate data base on historical trend. How to do that?
Solution:
Find out the current month and the number of days in the month with time.Now()
and time.Date()
functions. Once you have determined the number of days in a the current calendar month, use a for loop to loop from day 1 to the end day of the month.
For example:
package main
import (
"fmt"
"time"
)
func main() {
// get the current month
year, month, _ := time.Now().Date()
fmt.Printf("Current month: [%v]\n", month)
// get the number of days of the current month
t := time.Date(year, month+1, 0, 0, 0, 0, 0, time.UTC)
fmt.Printf("Total number of days in [%v], [%v] is [%v]\n", year, month, t.Day())
// loop each day of the month
for day := 1; day <= t.Day(); day++ {
// do whatever you want here ...
fmt.Println(day, month, year)
}
}
Sample output:
Current month: [February]
Total number of days in [2016], [February] is [29]
1 February 2016
2 February 2016
3 February 2016
4 February 2016
5 February 2016
6 February 2016
7 February 2016
8 February 2016
9 February 2016
10 February 2016
11 February 2016
12 February 2016
13 February 2016
14 February 2016
15 February 2016
16 February 2016
17 February 2016
18 February 2016
19 February 2016
20 February 2016
21 February 2016
22 February 2016
23 February 2016
24 February 2016
25 February 2016
26 February 2016
27 February 2016
28 February 2016
29 February 2016
Happy Coding!
References:
https://groups.google.com/forum/#!topic/golang-nuts/Hxdo-iLGp2Q
https://socketloop.com/tutorials/golang-how-to-get-year-month-and-day
See also : Golang : Calculate elapsed years or months since a date
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
+3.4k Java : Get FX sentiment from website example
+12k Golang : How to check if a string starts or ends with certain characters or words?
+19.5k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+9.2k Golang : Convert(cast) string to int64
+6.3k Unix/Linux : How to get own IP address ?
+10.1k Golang : Meaning of omitempty in struct's field tag
+18.7k Golang : When to use public and private identifier(variable) and how to make the identifier public or private?
+8.7k Golang : Handle sub domain with Gin
+11.8k Golang : Get remaining text such as id or filename after last segment in URL path
+7k Golang : Of hash table and hash map
+7.3k Golang : Command line ticker to show work in progress
+5.5k Golang : ROT32768 (rotate by 0x80) UTF-8 strings example