time_helper.go 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package utils
  2. import (
  3. "encoding/binary"
  4. "flag"
  5. "log"
  6. "net"
  7. "time"
  8. )
  9. const ntpEpochOffset = 2208988800
  10. type packet struct {
  11. Settings uint8
  12. Stratum uint8
  13. Poll int8
  14. Precision int8
  15. RootDelay uint32
  16. RootDispersion uint32
  17. ReferenceID uint32
  18. RefTimeSec uint32
  19. RefTimeFrac uint32
  20. OrigTimeSec uint32
  21. OrigTimeFrac uint32
  22. RxTimeSec uint32
  23. RxTimeFrac uint32
  24. TxTimeSec uint32
  25. TxTimeFrac uint32
  26. }
  27. // day 当天凌晨0点
  28. func ZeroHourTimeOfDay(day time.Time) time.Time {
  29. dayStr := day.Format("2006-01-02")
  30. zeroHourTime, _ := ParseTimeStringToTime("2006-01-02", dayStr)
  31. return *zeroHourTime
  32. }
  33. // day 当月一号凌晨0点
  34. func BeginningOfMonth(day time.Time) time.Time {
  35. dayStr := day.Format("2006-01")
  36. monthTime, _ := ParseTimeStringToTime("2006-01", dayStr)
  37. return *monthTime
  38. }
  39. // 指定年月的月份的月初凌晨0点和月末23点59分59秒
  40. func MonthBeginningToEnd(year int, month int) (time.Time, time.Time) {
  41. beginningOfMonth := time.Date(year, time.Month(month), 1, 0, 0, 0, 0, time.Local)
  42. beginningOfNextMonth := beginningOfMonth.AddDate(0, 1, 0)
  43. endOfMonth := beginningOfNextMonth.Add(time.Duration(-1))
  44. return beginningOfMonth, endOfMonth
  45. }
  46. func GetNetTime() string {
  47. var host string
  48. flag.StringVar(&host, "e", "182.92.12.11:123", "NTP host")
  49. flag.Parse()
  50. conn, err := net.Dial("udp", host)
  51. if err != nil {
  52. log.Fatalf("failed to connect: %v", err)
  53. }
  54. defer conn.Close()
  55. if err := conn.SetDeadline(time.Now().Add(15 * time.Second)); err != nil {
  56. log.Fatalf("failed to set deadline: %v", err)
  57. }
  58. req := &packet{Settings: 0x1B}
  59. if err := binary.Write(conn, binary.BigEndian, req); err != nil {
  60. log.Fatalf("failed to send request: %v", err)
  61. }
  62. rsp := &packet{}
  63. if err := binary.Read(conn, binary.BigEndian, rsp); err != nil {
  64. log.Fatalf("failed to read server response: %v", err)
  65. }
  66. secs := float64(rsp.TxTimeSec) - ntpEpochOffset
  67. nanos := (int64(rsp.TxTimeFrac) * 1e9) >> 32
  68. showtime := time.Unix(int64(secs), nanos)
  69. return time.Unix(showtime.Unix(), 0).Format("2006-01-02 15:04:05")
  70. }