gconv_time.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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/internal/utils"
  10. "github.com/gogf/gf/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. // If no `format` given, it converts `any` using gtime.NewFromTimeStamp if `any` is numeric,
  43. // or using gtime.StrToTime if `any` is string.
  44. func GTime(any interface{}, format ...string) *gtime.Time {
  45. if any == nil {
  46. return nil
  47. }
  48. if v, ok := any.(apiGTime); ok {
  49. return v.GTime(format...)
  50. }
  51. // It's already this type.
  52. if len(format) == 0 {
  53. if v, ok := any.(*gtime.Time); ok {
  54. return v
  55. }
  56. if t, ok := any.(time.Time); ok {
  57. return gtime.New(t)
  58. }
  59. if t, ok := any.(*time.Time); ok {
  60. return gtime.New(t)
  61. }
  62. }
  63. s := String(any)
  64. if len(s) == 0 {
  65. return gtime.New()
  66. }
  67. // Priority conversion using given format.
  68. if len(format) > 0 {
  69. t, _ := gtime.StrToTimeFormat(s, format[0])
  70. return t
  71. }
  72. if utils.IsNumeric(s) {
  73. return gtime.NewFromTimeStamp(Int64(s))
  74. } else {
  75. t, _ := gtime.StrToTime(s)
  76. return t
  77. }
  78. }