utils.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package main
  2. import (
  3. "encoding/binary"
  4. "regexp"
  5. "time"
  6. )
  7. func Int32toByteArray(i int32) (arr [4]byte) {
  8. binary.BigEndian.PutUint32(arr[0:4], uint32(i))
  9. return
  10. }
  11. func Int64toByteArray(i int64) (arr [8]byte) {
  12. binary.BigEndian.PutUint64(arr[0:8], uint64(i))
  13. return
  14. }
  15. // Find all the words in a string
  16. // return [][2]int of index,length
  17. func find_words(text string) [][]int {
  18. word, _ := regexp.Compile("([A-Za-z]+)")
  19. return word.FindAllStringIndex(text, -1)
  20. }
  21. // int version of Abs
  22. func Abs(x int) int {
  23. if x < 0 {
  24. return -x
  25. }
  26. return x
  27. }
  28. // Adjust date to 2:00 AM
  29. func NormalizeDate(date *time.Time) {
  30. offset := time.Duration(date.Second())*time.Second +
  31. time.Duration(date.Minute())*time.Minute +
  32. time.Duration(date.Hour()-2)*time.Hour +
  33. time.Duration(date.Nanosecond())*time.Nanosecond
  34. *date = date.Add(-offset)
  35. }
  36. // Find the 1st of the Month (Normalized) 2:00 AM
  37. func FirstOfMonthDate(date *time.Time) {
  38. if date.Day() != 1 {
  39. *date = date.AddDate(0, 0, 1-date.Day())
  40. }
  41. NormalizeDate(date)
  42. }
  43. // Find 1st of the Month (Normalize) Unix
  44. func FirstOfMonthDateUnix(dateUnix *int64) {
  45. var date time.Time = time.Unix(*dateUnix, 0)
  46. FirstOfMonthDate(&date)
  47. *dateUnix = date.Unix()
  48. }
  49. // See:
  50. // https://yourbasic.org/golang/format-parse-string-time-date-example/
  51. // for all your time.Time.Format needs.
  52. func FormatDate(dateUnix int64, format string) string {
  53. var date time.Time = time.Unix(dateUnix, 0)
  54. return date.Format(format)
  55. }
  56. func CurrentMonth(date time.Time) string {
  57. return date.Format("January")
  58. }