time.go 1.56 KB
Newer Older
hujiebin's avatar
hujiebin committed
1 2
package utils

hujiebin's avatar
hujiebin committed
3 4 5 6
import (
	"github.com/jinzhu/now"
	"time"
)
hujiebin's avatar
hujiebin committed
7 8 9 10 11

const DEFAULT_LANG = "en"
const DATETIME_FORMAT = "2006-01-02 15:04:05"
const COMPACT_DATE_FORMAT = "20060102"
const DATE_FORMAT = "2006-01-02"
hujiebin's avatar
hujiebin committed
12
const COMPACT_MONTH_FORMAT = "200601"
hujiebin's avatar
hujiebin committed
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28

func GetZeroTime(t time.Time) time.Time {
	return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
}

// 取最近的一个星期n
func GetLastDayOfWeek(t time.Time, n time.Weekday) time.Time {
	weekDay := t.Weekday()
	// 校正日期
	if weekDay < n {
		weekDay = 7 - n + weekDay
	} else {
		weekDay = weekDay - n
	}
	return t.AddDate(0, 0, -(int(weekDay)))
}
hujiebin's avatar
hujiebin committed
29 30 31 32

func GetMonday(t time.Time) time.Time {
	return GetLastDayOfWeek(t, time.Monday)
}
hujiebin's avatar
hujiebin committed
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55

// 增加年/月
// 因为golang原生的Time.AddDate增加月份的时候有bug
func AddDate(t time.Time, years int, months int) time.Time {
	year, month, day := t.Date()
	hour, min, sec := t.Clock()

	// firstDayOfMonthAfterAddDate: years 年,months 月后的 那个月份的1号
	firstDayOfMonthAfterAddDate := time.Date(year+years, month+time.Month(months), 1,
		hour, min, sec, t.Nanosecond(), t.Location())
	// firstDayOfMonthAfterAddDate 月份的最后一天
	lastDay := now.New(firstDayOfMonthAfterAddDate).EndOfMonth().Day()

	// 如果 t 的天 > lastDay,则设置为lastDay
	// 如:t 为 2020-03-31 12:00:00 +0800,增加1个月,为4月31号
	// 但是4月没有31号,则设置为4月最后一天lastDay(30号)
	if day > lastDay {
		day = lastDay
	}

	return time.Date(year+years, month+time.Month(months), day,
		hour, min, sec, t.Nanosecond(), t.Location())
}