Created
August 27, 2021 02:37
-
-
Save linw1995/9b2e7d53dcf4706279341bb3597dda01 to your computer and use it in GitHub Desktop.
get begin time and end time in Golang.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
func main() { | |
now := time.Now() | |
fmt.Println( | |
now.Truncate(time.Hour*24), | |
now.Truncate(time.Hour*24).Add(time.Hour*23+time.Minute*59+time.Second*59), | |
now, | |
) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
func main() { | |
now := time.Now() | |
fmt.Println( | |
now.AddDate(0, 0, 1-now.Day()).Truncate(time.Hour*24), | |
now.AddDate(0, 1, -now.Day()).Truncate(time.Hour*24).Add(time.Hour*23+time.Minute*59+time.Second*59), | |
now, | |
) | |
} |
New method
package main
import (
"fmt"
"time"
)
// TimeIn returns the time in UTC if the name is "" or "UTC".
// It returns the local time if the name is "Local".
// Otherwise, the name is taken to be a location name in
// the IANA Time Zone database, such as "Africa/Lagos".
func TimeIn(t time.Time, name string) (time.Time, error) {
loc, err := time.LoadLocation(name)
if err == nil {
t = t.In(loc)
}
return t, err
}
func InMonth(dt time.Time) (st, et time.Time) {
st = time.Date(dt.Year(), dt.Month(), 1, 0, 0, 0, 0, dt.Location())
et = time.Date(dt.Year(), dt.Month(), 1, 23, 59, 59, 0, dt.Location())
et = et.AddDate(0, 1, -1)
return
}
func main() {
now := time.Now()
fakelocal, _ := TimeIn(now, "Asia/Shanghai")
monthBegin, monthEnd := InMonth(fakelocal)
fmt.Println(monthBegin, monthEnd)
}
// You can edit this code!
// Click here and start typing.
package main
import (
"fmt"
"time"
)
func MonthDays(firstDayOfMonth time.Time) int {
diff := firstDayOfMonth.AddDate(0, 1, 0).Sub(firstDayOfMonth)
return int(diff.Hours()) / 24
}
func main() {
t, err := time.ParseInLocation("2006-01", "2019-12", time.Local)
if err != nil {
panic(err)
}
fmt.Println("Hello, 世界", MonthDays(t))
}
thanks for sharing
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Only work in local time is UTC……