golang一些日期区间函数

2020-12-15  本文已影响0人  EasyNetCN
import (
    "math"
    "time"
)

func GetFirstDateOfMonth(d time.Time) time.Time {
    d = d.AddDate(0, 0, -d.Day()+1)

    return GetZeroTime(d)
}

func GetLastDateOfMonth(d time.Time) time.Time {
    return GetFirstDateOfMonth(d).AddDate(0, 1, -1)
}

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

func GetFirstDateOfWeek(d time.Time) time.Time {
    offset := int(time.Monday - d.Weekday())

    if offset > 0 {
        offset = -6
    }

    return time.Date(d.Year(), d.Month(), d.Day(), 0, 0, 0, 0, d.Location()).AddDate(0, 0, offset)
}

func GetLastDateOfWeek(d time.Time) time.Time {
    offset := int(7 - d.Weekday())

    if offset > 6 {
        offset = 0
    }

    return time.Date(d.Year(), d.Month(), d.Day(), 0, 0, 0, 0, d.Location()).AddDate(0, 0, offset)
}

func GetWeekOfYear(d time.Time) int {
    return int(math.Ceil(GetLastDateOfWeek(d).Sub(GetLastDateOfWeek(time.Date(d.Year(), 1, 1, 0, 0, 0, 0, d.Location()))).Hours()/(24*7))) + 1
}
上一篇下一篇

猜你喜欢

热点阅读