time.go 2.13 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"
chenweijian's avatar
chenweijian committed
13
const MONTH_FORMAT = "2006-01"
hujiebin's avatar
hujiebin committed
14

chenweijian's avatar
chenweijian committed
15 16 17
// 获取沙特时区
var CstZone = time.FixedZone("CST", 3*3600) // 东三

hujiebin's avatar
hujiebin committed
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
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
33 34 35 36

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

// 增加年/月
// 因为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())
chenweijian's avatar
chenweijian committed
59 60 61 62 63 64
}

// 当天结束剩余秒数
func DayRemainSecond(date time.Time) int64 {
	return time.Date(date.Year(), date.Month(), date.Day(), 23, 59, 59, 999, date.Location()).Unix() - date.Unix()
}
65 66 67 68 69 70 71

func GetLastMonthStart(t time.Time) time.Time {
	thisMonthStart := time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, t.Location())
	lastDay := thisMonthStart.AddDate(0, 0, -1)
	lastMonthStart := time.Date(lastDay.Year(), lastDay.Month(), 1, 0, 0, 0, 0, t.Location())
	return lastMonthStart
}