推荐一个非常优秀的包 github.com/jinzhu/now
基本用法
time.Now() // 2013-11-18 17:51:49.123456789 Mon
BeginningOfMinute() // 2013-11-18 17:51:00 Mon
BeginningOfHour() // 2013-11-18 17:00:00 Mon
BeginningOfDay() // 2013-11-18 00:00:00 Mon
BeginningOfWeek() // 2013-11-17 00:00:00 Sun
WeekStartDay = time.Monday // Set Monday as first day
BeginningOfWeek() // 2013-11-18 00:00:00 Mon
BeginningOfMonth() // 2013-11-01 00:00:00 Fri
BeginningOfQuarter() // 2013-10-01 00:00:00 Tue
BeginningOfYear() // 2013-01-01 00:00:00 Tue
EndOfMinute() // 2013-11-18 17:51:59.999999999 Mon
EndOfHour() // 2013-11-18 17:59:59.999999999 Mon
EndOfDay() // 2013-11-18 23:59:59.999999999 Mon
EndOfWeek() // 2013-11-23 23:59:59.999999999 Sat
WeekStartDay = time.Monday // Set Monday as first day
EndOfWeek() // 2013-11-24 23:59:59.999999999 Sun
EndOfMonth() // 2013-11-30 23:59:59.999999999 Sat
EndOfQuarter() // 2013-12-31 23:59:59.999999999 Tue
EndOfYear() // 2013-12-31 23:59:59.999999999 Tue
// Use another time
t := time.Date(2013, 02, 18, 17, 51, 49, 123456789, time.UTC)
With(t).EndOfMonth() // 2013-02-28 23:59:59.999999999 Thu
Monday() // 2013-11-18 00:00:00 Mon
Sunday() // 2013-11-24 00:00:00 Sun
EndOfSunday() // 2013-11-24 23:59:59.999999999 Sun
使用中遇到时区问题
const YYYYMMDD = "2006-01-02" // 日期格式
time.Local, _ = time.LoadLocation("Asia/Shanghai")
t, err := time.Parse(YYYYMMDD, "2020-04-30")
if err != nil {
panic(err)
}
at1 := now.With(t).EndOfDay()
at2 := now.With(now.New(t).In(time.Local)).EndOfDay()
fmt.Printf("at1:%+v\nat2:%+v\n", at1, at2)
以上代码输出时区不一致
at1:2020-04-30 23:59:59.999999999 +0000 UTC // 格林时区,默认的时区
at2:2020-04-30 23:59:59.999999999 +0800 CST // 中国时区,注意后面有一个+0800,东八区时间
如果要改变时区的话,需要自己指定时区
// 输出某一天的北京时间 t是表示你的某一天时间,见上面代码。
now.With(now.New(t).In(time.Local)).EndOfDay()
// 输出当前的北京时间
now.With(now.New(time.Now()).In(time.Local)).EndOfDay()
网友评论