dbdate_test.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package main
  2. import "testing"
  3. func TestDBDate(t *testing.T) {
  4. table := map[DBDate][5]int{
  5. DBDate(20220127): {2022, 1, 27, 20220101, 20220131},
  6. DBDate(22000220): {2200, 2, 20, 22000201, 22000228}, // Not a leap year
  7. DBDate(20200217): {2020, 2, 17, 20200201, 20200229}, // 2020 Leap year
  8. DBDate(19991031): {1999, 10, 31, 19991001, 19991031},
  9. DBDate(19900228): {1990, 2, 28, 19900201, 19900228},
  10. DBDate(20381231): {2038, 12, 31, 20381201, 20381231},
  11. }
  12. for d, ts := range table {
  13. newDate := NewDBDate(ts[0], ts[1], ts[2])
  14. if newDate != d {
  15. t.Errorf("NewDBDate %v, got %v expected %v\n",
  16. ts, newDate, d)
  17. }
  18. year, month, day := newDate.YMD()
  19. if (year != ts[0]) || (month != ts[1]) || (day != ts[2]) {
  20. t.Errorf("YMD %v, got %d,%d,%d expected %v\n",
  21. newDate, year, month, day, ts)
  22. }
  23. // convert DBDate to time.Time
  24. newTime := DBDateTime(d)
  25. // convert time.Time to DBDate
  26. dateFromTime := ToDBDate(newTime)
  27. if newTime.Year() != ts[0] {
  28. t.Errorf("DBDateTime %v, Year got %d expected %d\n", d, newTime.Year(), ts[0])
  29. }
  30. if int(newTime.Month()) != ts[1] {
  31. t.Errorf("DBDateTime %v, Month got %d expected %d\n", d, newTime.Month(), ts[1])
  32. }
  33. if newTime.Day() != ts[2] {
  34. t.Errorf("DBDateTime %v, Day got %d expected %d\n", d, newTime.Day(), ts[2])
  35. }
  36. if newTime.Year() != newDate.Year() {
  37. t.Errorf("Year %v, got %d and %d\n",
  38. d, newTime.Year(), newDate.Year())
  39. }
  40. if int(newTime.Month()) != newDate.Month() {
  41. t.Errorf("Month %v, got %d and %d\n",
  42. d, newTime.Month(), newDate.Month())
  43. }
  44. if newTime.Day() != newDate.Day() {
  45. t.Errorf("Year %v, got %d and %d\n",
  46. d, newTime.Day(), newDate.Day())
  47. }
  48. if dateFromTime.Year() != newDate.Year() {
  49. t.Errorf("DFT Year %v, got %d and %d\n",
  50. d, dateFromTime.Year(), newDate.Year())
  51. }
  52. if dateFromTime.Month() != newDate.Month() {
  53. t.Errorf("DFT Month %v, got %d and %d\n",
  54. d, dateFromTime.Month(), newDate.Month())
  55. }
  56. if dateFromTime.Day() != newDate.Day() {
  57. t.Errorf("DFT Year %v, got %d and %d\n",
  58. d, dateFromTime.Day(), newDate.Day())
  59. }
  60. newDate.First()
  61. if int(newDate) != ts[3] {
  62. t.Errorf("First %v, got %d, expected %d\n",
  63. d, newDate, ts[3])
  64. }
  65. newDate.Last()
  66. if int(newDate) != ts[4] {
  67. t.Errorf("Last %v, got %d, expected %d\n",
  68. d, newDate, ts[4])
  69. }
  70. }
  71. }