MinuteToDataTime.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package lib
  2. import (
  3. "strconv"
  4. "time"
  5. )
  6. /*
  7. 时间常量
  8. */
  9. const (
  10. //定义每分钟的秒数
  11. SecondsPerMinute = 60
  12. //定义每小时的秒数
  13. SecondsPerHour = SecondsPerMinute * 60
  14. //定义每天的秒数
  15. SecondsPerDay = SecondsPerHour * 24
  16. )
  17. /*
  18. 时间转换函数
  19. */
  20. func resolveTime(seconds int) (day int, hour int, minute int, second int) {
  21. //秒
  22. second = seconds % 60
  23. //天
  24. day = seconds / SecondsPerDay
  25. seconds -= day * SecondsPerDay
  26. //时
  27. hour = seconds / SecondsPerHour
  28. seconds -= hour * SecondsPerHour
  29. //分
  30. minute = seconds / SecondsPerMinute
  31. seconds -= minute * SecondsPerHour
  32. return
  33. }
  34. func MinuteToDataTime(t int) string {
  35. str := ""
  36. day, hour, minute, second := resolveTime(t)
  37. if day > 0 {
  38. str += strconv.Itoa(day) + "天 "
  39. }
  40. if hour > 0 {
  41. str += strconv.Itoa(hour) + "小时 "
  42. }
  43. if minute > 0 {
  44. str += strconv.Itoa(minute) + "分钟 "
  45. }
  46. if second > 0 {
  47. str += strconv.Itoa(second) + "秒"
  48. }
  49. return str
  50. }
  51. func TimeSinceToString(startTime, endTime time.Time) string {
  52. str := ""
  53. // 计算时间差
  54. duration := endTime.Sub(startTime)
  55. // 将时间差表示为天、小时和分钟
  56. days := int(duration.Hours() / 24)
  57. hours := int(duration.Hours()) % 24
  58. minutes := int(duration.Minutes()) % 60
  59. seconds := int(duration.Seconds()) % 60
  60. //fmt.Printf("时间差为 %d 天 %d 小时 %d 分钟\n", days, hours, minutes)
  61. if days > 0 {
  62. str += strconv.Itoa(days) + "天 "
  63. }
  64. if hours > 0 {
  65. str += strconv.Itoa(hours) + "小时 "
  66. }
  67. if minutes > 0 {
  68. str += strconv.Itoa(minutes) + "分钟 "
  69. }
  70. if seconds > 0 {
  71. str += strconv.Itoa(seconds) + "秒 "
  72. }
  73. return str
  74. }