MinuteToDataTime.go 1.6 KB

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