gconv_time.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package gconv
  7. import (
  8. "time"
  9. "github.com/gogf/gf/v2/internal/utils"
  10. "github.com/gogf/gf/v2/os/gtime"
  11. )
  12. // Time converts `any` to time.Time.
  13. func Time(any interface{}, format ...string) time.Time {
  14. // It's already this type.
  15. if len(format) == 0 {
  16. if v, ok := any.(time.Time); ok {
  17. return v
  18. }
  19. }
  20. if t := GTime(any, format...); t != nil {
  21. return t.Time
  22. }
  23. return time.Time{}
  24. }
  25. // Duration converts `any` to time.Duration.
  26. // If `any` is string, then it uses time.ParseDuration to convert it.
  27. // If `any` is numeric, then it converts `any` as nanoseconds.
  28. func Duration(any interface{}) time.Duration {
  29. // It's already this type.
  30. if v, ok := any.(time.Duration); ok {
  31. return v
  32. }
  33. s := String(any)
  34. if !utils.IsNumeric(s) {
  35. d, _ := gtime.ParseDuration(s)
  36. return d
  37. }
  38. return time.Duration(Int64(any))
  39. }
  40. // GTime converts `any` to *gtime.Time.
  41. // The parameter `format` can be used to specify the format of `any`.
  42. // It returns the converted value that matched the first format of the formats slice.
  43. // If no `format` given, it converts `any` using gtime.NewFromTimeStamp if `any` is numeric,
  44. // or using gtime.StrToTime if `any` is string.
  45. func GTime(any interface{}, format ...string) *gtime.Time {
  46. if any == nil {
  47. return nil
  48. }
  49. if v, ok := any.(iGTime); ok {
  50. return v.GTime(format...)
  51. }
  52. // It's already this type.
  53. if len(format) == 0 {
  54. if v, ok := any.(*gtime.Time); ok {
  55. return v
  56. }
  57. if t, ok := any.(time.Time); ok {
  58. return gtime.New(t)
  59. }
  60. if t, ok := any.(*time.Time); ok {
  61. return gtime.New(t)
  62. }
  63. }
  64. s := String(any)
  65. if len(s) == 0 {
  66. return gtime.New()
  67. }
  68. // Priority conversion using given format.
  69. if len(format) > 0 {
  70. for _, item := range format {
  71. t, err := gtime.StrToTimeFormat(s, item)
  72. if t != nil && err == nil {
  73. return t
  74. }
  75. }
  76. return nil
  77. }
  78. if utils.IsNumeric(s) {
  79. return gtime.NewFromTimeStamp(Int64(s))
  80. } else {
  81. t, _ := gtime.StrToTime(s)
  82. return t
  83. }
  84. }