date.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. package myth
  2. import (
  3. "time"
  4. )
  5. const (
  6. // TimeFmtLong yyyy-MM-dd hh:mm:ss
  7. TimeFmtLong = `2006-01-02 15:04:05`
  8. // TimeFmtNumeric yyyyMMddhhmmss
  9. TimeFmtNumeric = `20060102150405`
  10. // DateFmtLong yyyy-MM-dd
  11. DateFmtLong = `2006-01-02`
  12. // DateFmtNumeric yyyyMMdd
  13. DateFmtNumeric = `20060102`
  14. )
  15. // 时间日期格式长度
  16. const (
  17. TimeLength = 19
  18. DateLength = 10
  19. )
  20. // IsTime 是否时间格式字符串
  21. func IsTime(s string) bool {
  22. if _, err := time.Parse(TimeFmtLong, s); err != nil {
  23. return false
  24. }
  25. return true
  26. }
  27. // IsDate 是否为有效日期
  28. func IsDate(s string) bool {
  29. if _, e := time.Parse(`2006-01-02`, s); e != nil {
  30. return false
  31. }
  32. return true
  33. }
  34. // StrToTime 字符串转时间
  35. func StrToTime(s string) (t time.Time, err error) {
  36. t, err = time.Parse(TimeFmtLong, s)
  37. return
  38. }
  39. // StrFmtTime 时间转字符串
  40. func StrFmtTime(s, fmt string) (t time.Time, err error) {
  41. t, err = time.Parse(fmt, s)
  42. return
  43. }
  44. // TimeToStr 时间转字符串
  45. func TimeToStr(t time.Time) string {
  46. return t.Format(TimeFmtLong)
  47. }
  48. // TimeFmtStr 时间转字符串
  49. func TimeFmtStr(t time.Time, fmt string) string {
  50. return t.Format(fmt)
  51. }
  52. // StrToDate 字符串转日期
  53. func StrToDate(s string) (t time.Time, err error) {
  54. t, err = time.Parse(DateFmtLong, s)
  55. return
  56. }
  57. // StrToLocationTime 字符串转时间
  58. func StrToLocationTime(s string) (t time.Time, err error) {
  59. t, err = time.ParseInLocation(TimeFmtLong, s, time.Local)
  60. return
  61. }
  62. // StrFmtLocationTime 字符串转时间
  63. func StrFmtLocationTime(s, fmt string) (t time.Time, err error) {
  64. t, err = time.ParseInLocation(fmt, s, time.Local)
  65. return
  66. }
  67. // StrToLocationDate 字符串转日期
  68. func StrToLocationDate(s string) (t time.Time, err error) {
  69. t, err = time.ParseInLocation(DateFmtLong, s, time.Local)
  70. return
  71. }
  72. // Unix returns the local Time corresponding to the given Unix time, sec seconds and nsec nanoseconds since January 1, 1970 UTC.
  73. func Unix(sec, nsec int64) time.Time {
  74. return time.Unix(sec, nsec)
  75. }
  76. // IsWeekEnd 日期是否周末
  77. func IsWeekEnd(d time.Weekday) bool {
  78. day := int(d)
  79. if day == 6 || day == 0 {
  80. return true
  81. }
  82. return false
  83. }