去评论
dz插件网

Golang实用封装函数集一

婷姐
2023/04/21 16:12:08
取上月/周开始、结束时间:
1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

func get_lastmonth_begin_end() (map[string]interface{} ) {
     
   now := time.Now()
   lastMonthFirstDay := now.AddDate(0, -1, -now.Day()+1)//利用此特性,可以得到上周 now.AddDate(0, 0, -int(now.Weekday())-6)的开始时间
   lastMonthStart := time.Date(lastMonthFirstDay.Year(), lastMonthFirstDay.Month(), lastMonthFirstDay.Day(), 0, 0, 0, 0, now.Location()).Unix()
   lastMonthEndDay := lastMonthFirstDay.AddDate(0, 1, -1)
   lastMonthEnd := time.Date(lastMonthEndDay.Year(), lastMonthEndDay.Month(), lastMonthEndDay.Day(), 23, 59, 59, 0, now.Location()).Unix()

     
    ret := make(map[string]interface{})
    ret["time_begin_format"] = time.Unix(lastMonthStart, 0).Format("2006-01-02 15:04:05")
    ret["time_end_format"]   = time.Unix(lastMonthEnd, 0).Format("2006-01-02 15:04:05")
     
  
    ret["time_begin"]        = lastMonthStart
    ret["time_end"]          = lastMonthEnd
     
    return ret
}
执行结果:
map[time_begin_format:2020-12-01 00:00:00 time_end_format:2020-12-31 23:59:59 time_begin:1606752000 time_end:1609430399]




取本周一,周末时间:
1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

func get_weekday_begin_end() (map[string]interface{} ) {
    now := time.Now()

    offset := int(time.Monday - now.Weekday())
  
    weekStartDate := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, offset)
    weekMonday := weekStartDate.Format("2006-01-02")

    TimeMonday, _ := time.Parse("2006-01-02", weekMonday)
    lastWeekMonday := TimeMonday.AddDate(0, 0, 6)
    enddate := time.Date(lastWeekMonday.Year(), lastWeekMonday.Month(), lastWeekMonday.Day(), 23, 59, 59, 0, time.Local)
    end := enddate.Format("2006-01-02 15:04:05")
     
     
    ret := make(map[string]interface{})
    ret["time_begin_format"] = weekMonday
    ret["time_end_format"]  = end
     
  
    ret["time_begin"]    = weekStartDate.Unix()
    ret["time_end"]     = enddate.Unix()
     
    return ret
}

执行结果:
map[time_begin_format:2021-01-18 time_end_format:2021-01-24 23:59:59 time_begin:1610899200 time_end:1611503999]