gitea源码

sec_to_time.go 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // Copyright 2022 Gitea. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package util
  4. import (
  5. "fmt"
  6. "strings"
  7. )
  8. // SecToHours converts an amount of seconds to a human-readable hours string.
  9. // This is stable for planning and managing timesheets.
  10. // Here it only supports hours and minutes, because a work day could contain 6 or 7 or 8 hours.
  11. // If the duration is less than 1 minute, it will be shown as seconds.
  12. func SecToHours(durationVal any) string {
  13. seconds, _ := ToInt64(durationVal)
  14. hours := seconds / 3600
  15. minutes := (seconds / 60) % 60
  16. formattedTime := ""
  17. formattedTime = formatTime(hours, "hour", formattedTime)
  18. formattedTime = formatTime(minutes, "minute", formattedTime)
  19. // The formatTime() function always appends a space at the end. This will be trimmed
  20. if formattedTime == "" && seconds > 0 {
  21. formattedTime = formatTime(seconds, "second", "")
  22. }
  23. return strings.TrimRight(formattedTime, " ")
  24. }
  25. // formatTime appends the given value to the existing forammattedTime. E.g:
  26. // formattedTime = "1 year"
  27. // input: value = 3, name = "month"
  28. // output will be "1 year 3 months "
  29. func formatTime(value int64, name, formattedTime string) string {
  30. if value == 1 {
  31. formattedTime = fmt.Sprintf("%s1 %s ", formattedTime, name)
  32. } else if value > 1 {
  33. formattedTime = fmt.Sprintf("%s%d %ss ", formattedTime, value, name)
  34. }
  35. return formattedTime
  36. }