time.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package timeutil
  2. import (
  3. "errors"
  4. "fmt"
  5. "strings"
  6. "time"
  7. )
  8. func Parse(timeStrInput string) (res time.Time, err error) {
  9. if len(timeStrInput) > 0 {
  10. timeStr := strings.ReplaceAll(timeStrInput, "/", "")
  11. timeStr = strings.ReplaceAll(timeStr, "-", "")
  12. if len(timeStr) == 8 {
  13. res, err = time.Parse("20060102", timeStr)
  14. } else if len(timeStr) == 11 {
  15. res, err = time.Parse("20060102 15", timeStr)
  16. } else if len(timeStr) == 14 {
  17. res, err = time.Parse("20060102 15:04", timeStr)
  18. } else if len(timeStr) == 17 {
  19. res, err = time.Parse("20060102 15:04:05", timeStr)
  20. } else if len(timeStr) == 21 {
  21. res, err = time.Parse("20060102 15:04:05.000", timeStr)
  22. } else {
  23. err = errors.New("bad value for timeStr")
  24. }
  25. if err != nil {
  26. timeStr = strings.ReplaceAll(timeStrInput, "-", "/")
  27. if len(timeStr) == 8 {
  28. res, err = time.Parse("2006/1/2", timeStr)
  29. } else if len(timeStr) == 9 {
  30. res, err = time.Parse("2006/01/2", timeStr)
  31. if err != nil {
  32. res, err = time.Parse("2006/1/02", timeStr)
  33. }
  34. } else if len(timeStr) == 11 {
  35. res, err = time.Parse("2006/1/2 15", timeStr)
  36. } else if len(timeStr) == 12 {
  37. res, err = time.Parse("2006/01/2 15", timeStr)
  38. if err != nil {
  39. res, err = time.Parse("2006/1/02 15", timeStr)
  40. }
  41. } else if len(timeStr) == 14 {
  42. res, err = time.Parse("2006/1/2 15:04", timeStr)
  43. } else if len(timeStr) == 15 {
  44. res, err = time.Parse("2006/1/02 15:04", timeStr)
  45. if err != nil {
  46. res, err = time.Parse("2006/01/2 15:04", timeStr)
  47. }
  48. } else if len(timeStr) == 17 {
  49. res, err = time.Parse("2006/1/2 15:04:05", timeStr)
  50. } else if len(timeStr) == 18 {
  51. res, err = time.Parse("2006/1/02 15:04:05", timeStr)
  52. if err != nil {
  53. res, err = time.Parse("2006/01/2 15:04:05", timeStr)
  54. }
  55. }
  56. }
  57. }
  58. return res, err
  59. }
  60. func SecondsToTime(seconds int) string {
  61. if seconds <= 0 {
  62. return "00:00:00"
  63. }
  64. hours := seconds / 3600
  65. seconds = seconds % 3600
  66. minutes := seconds / 60
  67. seconds = seconds % 60
  68. return fmt.Sprintf("%02d:%02d:%02d", hours, minutes, seconds)
  69. }