date.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. //日期处理工具类
  2. package util
  3. import (
  4. "fmt"
  5. "time"
  6. )
  7. const (
  8. Date_Full_Layout = "2006-01-02 15:04:05"
  9. Date_Short_Layout = "2006-01-02"
  10. Date_Small_Layout = "01-02"
  11. Date_Time_Layout = "15:04"
  12. Date_yyyyMMdd = "20060102"
  13. Date_yyyyMMdd_Point = "2006.01.02"
  14. )
  15. //当前日期格式化
  16. func NowFormat(layout string) string {
  17. return time.Now().Local().Format(layout)
  18. }
  19. //日期格式化
  20. func FormatDate(src *time.Time, layout string) string {
  21. return (*src).Local().Format(layout)
  22. }
  23. //兼容从Java转换过来的数据,java生成的时间戳是按微秒算的,Go中只能按毫秒或纳秒算
  24. func formatDateWithInt64(src *int64, layout string) string {
  25. var tmp int64
  26. if *src > 0 {
  27. if len(fmt.Sprint(*src)) >= 12 {
  28. tmp = (*src) / 1000
  29. } else {
  30. tmp = (*src)
  31. }
  32. } else {
  33. if len(fmt.Sprint(*src)) >= 13 {
  34. tmp = (*src) / 1000
  35. } else {
  36. tmp = (*src)
  37. }
  38. }
  39. date := time.Unix(tmp, 0)
  40. return FormatDate(&date, layout)
  41. }
  42. func FormatDateByInt64(src *int64, layout string) string {
  43. var tmp int64
  44. if *src > 0 {
  45. if len(fmt.Sprint(*src)) >= 12 {
  46. tmp = (*src) / 1000
  47. } else {
  48. tmp = (*src)
  49. }
  50. } else {
  51. if len(fmt.Sprint(*src)) >= 13 {
  52. tmp = (*src) / 1000
  53. } else {
  54. tmp = (*src)
  55. }
  56. }
  57. date := time.Unix(tmp, 0)
  58. return FormatDate(&date, layout)
  59. }
  60. //支持源端多种格式
  61. func FormatDateWithObj(src *interface{}, layout string) string {
  62. if tmp, ok := (*src).(int64); ok {
  63. return formatDateWithInt64(&tmp, layout)
  64. } else if tmp2, ok2 := (*src).(float64); ok2 {
  65. tmpe := int64(tmp2)
  66. return formatDateWithInt64(&tmpe, layout)
  67. } else if tmp3, ok3 := (*src).(*time.Time); ok3 {
  68. return tmp3.Format(layout)
  69. } else {
  70. return ""
  71. }
  72. }