date.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. "time"
  6. "github.com/beanzilla/gonode"
  7. )
  8. type Date struct {
  9. N *gonode.Node `json:"-"`
  10. Day int `json:"day"`
  11. Month int `json:"month"`
  12. Year int `json:"year"`
  13. }
  14. func (d *Date) String() string {
  15. month := time.Month(d.Month)
  16. return fmt.Sprintf("%s %d, %d", month.String(), d.Day, d.Year)
  17. }
  18. func (d *Date) Parse(n *gonode.Node) error {
  19. txt := fmt.Sprintf("%v", n.Data())
  20. if !strings.HasPrefix(txt, "date") {
  21. return fmt.Errorf("node doesn't contain correct information, expected 'date ## ## ####' got '%s'", txt)
  22. }
  23. parts := strings.Split(txt, " ")
  24. if len(parts) < 4 {
  25. return fmt.Errorf("expected no less than 4 parts, got %d %v", len(parts), parts)
  26. }
  27. // 'date' parts[0] (Ignore this)
  28. // day parts[1]
  29. if !IsInt(parts[1]) {
  30. return fmt.Errorf("day is invalid, '%s'", parts[1])
  31. }
  32. d.Day = ValueInt(parts[1])
  33. // month parts[2]
  34. if !IsInt(parts[2]) {
  35. return fmt.Errorf("month is invalid, '%s'", parts[2])
  36. }
  37. d.Month = ValueInt(parts[2])
  38. // year parts[3]
  39. if !IsInt(parts[3]) {
  40. return fmt.Errorf("year is invalid, '%s'", parts[3])
  41. }
  42. d.Year = ValueInt(parts[3])
  43. d.N = n
  44. return nil
  45. }
  46. func (d *Date) Update() error {
  47. if d.N == nil {
  48. return fmt.Errorf("no node associated, can't update")
  49. }
  50. d.N.SetData(fmt.Sprintf("date %d %d %d", d.Day, d.Month, d.Year))
  51. return nil
  52. }