exprinter.go 1.8 KB

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