美文网首页
golang一些日期区间函数

golang一些日期区间函数

作者: EasyNetCN | 来源:发表于2020-12-15 16:45 被阅读0次
    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
    }
    

    相关文章

      网友评论

          本文标题:golang一些日期区间函数

          本文链接:https://www.haomeiwen.com/subject/rkmwgktx.html