util.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package util
  2. import (
  3. "fmt"
  4. "math"
  5. "time"
  6. )
  7. const (
  8. LocationName = "Asia/Shanghai"
  9. LayoutTime = "2006-01-02 15:04:05"
  10. Layout = "2006-01-02"
  11. )
  12. // TimeParseLocalUnix 获取当天零点的时间戳
  13. // eg 2023-02-22 => 1676995200
  14. func TimeParseLocalUnix(DayTime string) int64 {
  15. value := DayTime
  16. if len(DayTime) <= 11 {
  17. value = fmt.Sprintf("%s 00:00:00", DayTime)
  18. }
  19. loc, _ := time.LoadLocation("Local")
  20. theTime, _ := time.ParseInLocation(LayoutTime, value, loc)
  21. return theTime.Unix()
  22. }
  23. // TimeParseLocalEndUnix 获取当天24点的时间戳
  24. // eg 2023-02-22 => 1676995200
  25. func TimeParseLocalEndUnix(DayTime string) int64 {
  26. value := DayTime
  27. if len(DayTime) <= 11 {
  28. value = fmt.Sprintf("%s 23:59:59", DayTime)
  29. }
  30. loc, _ := time.LoadLocation("Local")
  31. theTime, _ := time.ParseInLocation(LayoutTime, value, loc)
  32. return theTime.Unix()
  33. }
  34. // ConvertParseLocalUnix 字符串转换当天时间戳
  35. // eg 15:04:05 => 1676998245
  36. func ConvertParseLocalUnix(timeParse string) (int64, error) {
  37. loc, err := time.LoadLocation("Local")
  38. if err != nil {
  39. return 0, err
  40. }
  41. value := fmt.Sprintf("%s %s", time.Now().Format(Layout), timeParse)
  42. theTime, err := time.ParseInLocation(LayoutTime, value, loc)
  43. if err != nil {
  44. return 0, err
  45. }
  46. return theTime.Unix(), nil
  47. }
  48. // GetMonthRemainDay 获取当前月还剩几天
  49. func GetMonthRemainDay() int {
  50. now := time.Now()
  51. lastDayOfMonth := time.Date(now.Year(), now.Month()+1, 0, 23, 59, 59, 999999999, now.Location())
  52. return int(lastDayOfMonth.Sub(now).Hours()/24) + 1
  53. }
  54. // Ceil 向上取整函数
  55. func Ceil(x float64) float64 {
  56. // 使用 math.Floor 计算小于或等于 x 的最大整数
  57. // 然后检查 x 是否为整数,如果不是,则结果加 1
  58. // 注意:math.Floor 返回的是 float64 类型,所以我们需要进行比较
  59. // 来确定是否需要加 1
  60. intPart := math.Floor(x)
  61. if x-intPart > 0 {
  62. return intPart + 1
  63. }
  64. return intPart
  65. }