time.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Copyright 2015 The Xorm Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package dialects
  5. import (
  6. "time"
  7. "xorm.io/xorm/schemas"
  8. )
  9. // FormatTime format time as column type
  10. func FormatTime(dialect Dialect, sqlTypeName string, t time.Time) (v interface{}) {
  11. switch sqlTypeName {
  12. case schemas.Time:
  13. s := t.Format("2006-01-02 15:04:05") // time.RFC3339
  14. v = s[11:19]
  15. case schemas.Date:
  16. v = t.Format("2006-01-02")
  17. case schemas.DateTime, schemas.TimeStamp, schemas.Varchar: // !DarthPestilane! format time when sqlTypeName is schemas.Varchar.
  18. v = t.Format("2006-01-02 15:04:05")
  19. case schemas.TimeStampz:
  20. if dialect.URI().DBType == schemas.MSSQL {
  21. v = t.Format("2006-01-02T15:04:05.9999999Z07:00")
  22. } else {
  23. v = t.Format(time.RFC3339Nano)
  24. }
  25. case schemas.BigInt, schemas.Int:
  26. v = t.Unix()
  27. default:
  28. v = t
  29. }
  30. return
  31. }
  32. func FormatColumnTime(dialect Dialect, defaultTimeZone *time.Location, col *schemas.Column, t time.Time) (v interface{}) {
  33. if t.IsZero() {
  34. if col.Nullable {
  35. return nil
  36. }
  37. return ""
  38. }
  39. if col.TimeZone != nil {
  40. return FormatTime(dialect, col.SQLType.Name, t.In(col.TimeZone))
  41. }
  42. return FormatTime(dialect, col.SQLType.Name, t.In(defaultTimeZone))
  43. }