ymd.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package main
  2. import "time"
  3. type YMD uint32
  4. type YM uint32
  5. // YYYYMM max 6 digits.
  6. // YYYYMMDD max 8 digits. int32.
  7. //
  8. // Store dates as uint32
  9. // YYYYMMDD
  10. //
  11. // So: Jan 21, 2022 => 20220121
  12. // Jan 2022 => 202201
  13. //
  14. func (d *YMD) Year() int {
  15. return int(*d) / 10000
  16. }
  17. func (d *YMD) Month() int {
  18. return (int(*d) / 100) % 100
  19. }
  20. func (d *YMD) Day() int {
  21. return int(*d) % 100
  22. }
  23. func (d *YMD) YM() YM {
  24. return YM(int(*d) / 100)
  25. }
  26. // Set day - does no validation
  27. func (d *YMD) SetDay(day int) {
  28. var i int = int(*d)
  29. i -= (i % 100)
  30. i += day
  31. *d = YMD(i)
  32. }
  33. // Make the first of the month
  34. func (d *YMD) First() {
  35. d.SetDay(1)
  36. }
  37. // Make end of month
  38. func (d *YMD) Last() {
  39. var value int = int(*d)
  40. // time.Date will normalize the date for us.
  41. // set Month +1, and day to 0 (gives us last day of previous month)
  42. var lastDay time.Time = time.Date(value/10000,
  43. time.Month((value/100)%100)+1,
  44. 0, 4, 3, 2, 1, time.Local)
  45. *d = YMD(lastDay.Year()*10000 +
  46. int(lastDay.Month())*100 + lastDay.Day())
  47. }
  48. func NewYMD(year, month, day int) YMD {
  49. return YMD(year*10000 + month*100 + day)
  50. }
  51. func (d *YMD) YMD() (int, int, int) {
  52. var i int = int(*d)
  53. return i / 10000, (i / 100) % 100, i % 100
  54. }
  55. func (d *YMD) Time() time.Time {
  56. var value int = int(*d)
  57. return time.Date(value/10000,
  58. time.Month((value/100)%100),
  59. value%100, 2, 2, 2, 0, time.Local)
  60. }
  61. // Convert time.Time to DBDate
  62. func NewYMDFromTime(point time.Time) YMD {
  63. return YMD(point.Year()*10000 +
  64. int(point.Month())*100 + point.Day())
  65. }
  66. // Convert DBDate to time.Time
  67. func ToTime(point YMD) time.Time {
  68. // I'm not sure about hours, minutes, seconds.
  69. var value int = int(point)
  70. var result time.Time = time.Date(value/10000,
  71. time.Month((value/100)%100),
  72. value%100, 2, 2, 2, 0, time.Local)
  73. return result
  74. }
  75. func NewYM(year, month int) YM {
  76. return YM(year*100 + month)
  77. }
  78. func (d *YM) Year() int {
  79. return int(*d) / 100
  80. }
  81. func (d *YM) Month() int {
  82. return int(*d) % 100
  83. }
  84. func (d *YM) YMD() YMD {
  85. return YMD(int(*d)*100 + 1)
  86. }