tprinter.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package timefmt
  2. import (
  3. "bytes"
  4. "git.swzry.com/zry/YAGTF/yagtf/tfelem"
  5. "time"
  6. )
  7. type TimeElement interface {
  8. PrintElement(t time.Time) string
  9. ExpectedSize() int
  10. }
  11. const bufSizeRedunt = 64
  12. type TimePrinter struct {
  13. elementList []TimeElement
  14. expectedSize int
  15. forceTz bool
  16. forceUTC bool
  17. forceLocal bool
  18. forceTzVal *time.Location
  19. }
  20. func (this *TimePrinter) UseArgumentSpecifiedTimezone() {
  21. this.forceTz = false
  22. }
  23. func (this *TimePrinter) UseTimezone(tz *time.Location) {
  24. this.forceTz = true
  25. this.forceLocal = false
  26. this.forceUTC = false
  27. this.forceTzVal = tz
  28. }
  29. func (this *TimePrinter) UseLocalTimezone() {
  30. this.forceTz = true
  31. this.forceLocal = true
  32. this.forceUTC = false
  33. }
  34. func (this *TimePrinter) UseUTC() {
  35. this.forceTz = true
  36. this.forceLocal = false
  37. this.forceUTC = true
  38. }
  39. func (this *TimePrinter) AddPureText(text string) {
  40. e := &tfelem.PureTextElement{
  41. PureText: text,
  42. }
  43. this.AddElement(e)
  44. }
  45. func (this *TimePrinter) AddElement(e TimeElement) {
  46. this.elementList = append(this.elementList, e)
  47. this.expectedSize += e.ExpectedSize()
  48. }
  49. func (this *TimePrinter) PrintTime(t time.Time) string {
  50. bsl := make([]byte, 0, this.expectedSize+bufSizeRedunt)
  51. buf := bytes.NewBuffer(bsl)
  52. ttz := t
  53. if this.forceTz {
  54. if this.forceLocal {
  55. ttz = t.Local()
  56. } else if this.forceUTC {
  57. ttz = t.UTC()
  58. } else {
  59. ttz = t.In(this.forceTzVal)
  60. }
  61. }
  62. for _, v := range this.elementList {
  63. buf.WriteString(v.PrintElement(ttz))
  64. }
  65. return buf.String()
  66. }
  67. func NewTimePrinter() *TimePrinter {
  68. tp := &TimePrinter{}
  69. tp.elementList = make([]TimeElement, 0)
  70. tp.expectedSize = 0
  71. return tp
  72. }