datetime.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package util
  2. import "time"
  3. const (
  4. // TimeFmtLong yyyy-MM-dd hh:mm:ss
  5. TimeFmtLong = `2006-01-02 15:04:05`
  6. // TimeFmtNumeric yyyyMMddhhmmss
  7. TimeFmtNumeric = `20060102150405`
  8. // DateFmtLong yyyy-MM-dd
  9. DateFmtLong = `2006-01-02`
  10. // DateFmtNumeric yyyyMMdd
  11. DateFmtNumeric = `20060102`
  12. )
  13. // IsTime 是否时间格式字符串
  14. func IsTime(s string) bool {
  15. if _, err := time.ParseInLocation(TimeFmtLong, s, time.Local); err != nil {
  16. return false
  17. }
  18. return true
  19. }
  20. // IsDate 是否为有效日期
  21. func IsDate(s string) bool {
  22. if _, e := time.ParseInLocation(DateFmtLong, s, time.Local); e != nil {
  23. return false
  24. }
  25. return true
  26. }
  27. // StrToTime 字符串转时间
  28. func StrToTime(s string) (t time.Time, err error) {
  29. t, err = time.ParseInLocation(TimeFmtLong, s, time.Local)
  30. return
  31. }
  32. // StrFmtTime 时间转字符串
  33. func StrFmtTime(s, fmt string) (t time.Time, err error) {
  34. t, err = time.ParseInLocation(fmt, s, time.Local)
  35. return
  36. }
  37. // TimeToStr 时间转字符串
  38. func TimeToStr(t time.Time) string {
  39. return t.Format(TimeFmtLong)
  40. }
  41. // TimeFmtStr 时间转字符串
  42. func TimeFmtStr(t time.Time, fmt string) string {
  43. return t.Format(fmt)
  44. }
  45. // StrToDate 字符串转日期
  46. func StrToDate(s string) (t time.Time, err error) {
  47. t, err = time.ParseInLocation(DateFmtLong, s, time.Local)
  48. return
  49. }
  50. // IsWeekEnd 日期是否周末
  51. func IsWeekEnd(d time.Weekday) bool {
  52. day := int(d)
  53. if day == 6 || day == 0 {
  54. return true
  55. }
  56. return false
  57. }