date.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. // IsWeekEnd 日期是否周末
  73. func IsWeekEnd(d time.Weekday) bool {
  74. day := int(d)
  75. if day == 6 || day == 0 {
  76. return true
  77. }
  78. return false
  79. }