123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126 |
- package utility
- import (
- "gadmin/config"
- "strings"
- "time"
- "github.com/jinzhu/now"
- )
- func GetBeginAndEndOfDay(date string) (begin, end int64, err error) {
- t, err := now.Parse(date) // 2017-10-13 00:00:00, nil
- if err != nil {
- return
- }
- begin = now.With(t).BeginningOfDay().Unix()
- end = now.With(t).EndOfDay().Unix()
- return
- }
- func GetBeginAndEndOfDay2(day, endDay string) (begin, end int64, err error) {
- t, err := now.Parse(day) // 2017-10-13 00:00:00, nil
- if err != nil {
- return
- }
- t2, err := now.Parse(endDay) // 2017-10-13 00:00:00, nil
- if err != nil {
- return
- }
- begin = now.With(t).BeginningOfDay().Unix()
- end = now.With(t2).EndOfDay().Unix()
- return
- }
- func Format(date time.Time) string {
- return date.In(config.DefaultZone).Format("2006-01-02")
- }
- func FormatSecond(date time.Time) string {
- return date.In(config.DefaultZone).Format("2006-01-02 15:04:05")
- }
- func ParseDate(date string) string {
- if i := strings.Index(date, "T"); i > 0 {
- return date[:i]
- }
- return date
- }
- func ParseDateToTime(date string) time.Time {
- return now.MustParse(ParseDate(date))
- }
- func ParseUnixStamp(date string) int64 {
- if i := strings.Index(date, "T"); i > 0 {
- return now.MustParse(date[:i]).Unix()
- }
- return 0
- }
- func WeekByDate(t time.Time) (week int) {
- yearDay := t.YearDay()
- yearFirstDay := t.AddDate(0, 0, -yearDay+1)
- firstDayInWeek := int(yearFirstDay.Weekday())
- //今年第一周有几天
- firstWeekDays := 1
- if firstDayInWeek != 0 {
- firstWeekDays = 7 - firstDayInWeek + 1
- }
- if yearDay <= firstWeekDays {
- week = 1
- } else {
- week = (yearDay-firstWeekDays)/7 + 2
- }
- return week
- }
- func CurrentWeek() (week int) {
- _, week = time.Now().ISOWeek()
- return week
- }
- func WeekIndexDate() string {
- n := time.Now()
- offset := int(time.Monday - n.Weekday())
- if offset > 0 {
- offset = -6
- }
- weekStart := time.Date(n.Year(), n.Month(), n.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, offset)
- return weekStart.Format("20060102")
- }
- func GetYearDay2(tm *time.Time) int {
- return tm.Year()*1000 + tm.YearDay()
- }
- func GetDaysBetween2Date(format, date1Str, date2Str string) (int, error) {
- // 将字符串转化为Time格式
- date1, err := time.ParseInLocation(format, date1Str, time.Local)
- if err != nil {
- return 0, err
- }
- // 将字符串转化为Time格式
- date2, err := time.ParseInLocation(format, date2Str, time.Local)
- if err != nil {
- return 0, err
- }
- //计算相差天数
- if date1.Unix() > date2.Unix() {
- return int(date1.Sub(date2).Hours() / 24), nil
- } else {
- return int(date2.Sub(date1).Hours() / 24), nil
- }
- }
- func MaxTime(time1, time2 time.Time) time.Time {
- if time1.After(time2) {
- return time1
- }
- return time2
- }
|