常用类型及数据操作方法
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

101 lines
2.3 KiB

3 years ago
  1. package helper
  2. import (
  3. "strconv"
  4. "time"
  5. )
  6. func FormatDateTime(str string) string {
  7. date, err := strconv.ParseInt(str, 10, 64)
  8. if err != nil {
  9. return ""
  10. }
  11. return time.Unix(date, 0).Format("2006-01-02 15:04:05")
  12. }
  13. func FormatDate(str string) string {
  14. date, err := strconv.ParseInt(str, 10, 64)
  15. if err != nil {
  16. return ""
  17. }
  18. return time.Unix(date, 0).Format("2006-01-02")
  19. }
  20. // 获取当天开始时间戳
  21. func GetTodayStartTimeStamp() int64 {
  22. var reserveTime time.Time
  23. // loc, _ := time.LoadLocation(time.Location.String())
  24. date := time.Now().Format("2006-01-02")
  25. reserveTime, _ = time.ParseInLocation("2006-01-02", date, time.Local)
  26. return reserveTime.Unix()
  27. }
  28. // 获取当天结束时间戳
  29. func GetTodayEndTimeStamp() int64 {
  30. var reserveTime time.Time
  31. // loc, _ := time.LoadLocation("Asia/Shanghai")
  32. date := time.Now().Format("2006-01-02")
  33. reserveTime, _ = time.ParseInLocation("2006-01-02 15:04:05", date+" 23:59:59", time.Local)
  34. return reserveTime.Unix()
  35. }
  36. // 获取本周开始时间戳
  37. func GetWeekStartTimeStamp() int64 {
  38. var reserveTime time.Time
  39. now := time.Now()
  40. loc, _ := time.LoadLocation("Asia/Shanghai")
  41. offset := int(time.Monday - now.Weekday())
  42. if offset > 0 {
  43. offset = -6
  44. }
  45. weekStartDate := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, offset)
  46. weekMonday := weekStartDate.Format("2006-01-02")
  47. reserveTime, _ = time.ParseInLocation("2006-01-02", weekMonday, loc)
  48. return reserveTime.Unix()
  49. }
  50. // 获取当月开始时间戳
  51. func GetMonthStartTimeStamp() int64 {
  52. var reserveTime time.Time
  53. loc, _ := time.LoadLocation("Asia/Shanghai")
  54. date := time.Now().Format("2006-01")
  55. reserveTime, _ = time.ParseInLocation("2006-01", date, loc)
  56. return reserveTime.Unix()
  57. }
  58. // RFC3339ToCSTLayout convert rfc3339 value to china standard time layout
  59. func RFC3339ToCSTLayout(value string) (string, error) {
  60. var (
  61. cst *time.Location
  62. )
  63. var err error
  64. if cst, err = time.LoadLocation("Asia/Shanghai"); err != nil {
  65. panic(err)
  66. }
  67. ts, err := time.Parse(time.RFC3339, value)
  68. if err != nil {
  69. return "", err
  70. }
  71. return ts.In(cst).Format("2006-01-02 15:04:05"), nil
  72. }
  73. // 具体日期时间转时间戳
  74. func DatetimeToUnix(value string) int64 {
  75. loc, _ := time.LoadLocation("Asia/Shanghai")
  76. reserveTime, _ := time.ParseInLocation("2006-01-02 15:04:05", value, loc)
  77. return reserveTime.Unix()
  78. }