timefmt.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package timefmt
  2. import (
  3. "strings"
  4. "time"
  5. )
  6. type TimeFormatter struct {
  7. Parser *FormatParser
  8. Printer *TimePrinter
  9. Multiline bool
  10. }
  11. func (this *TimeFormatter) Format(t time.Time) string {
  12. fs := this.Printer.PrintTime(t)
  13. if this.Multiline {
  14. return fs
  15. } else {
  16. fs = strings.Replace(fs, "\r", "", -1)
  17. fs = strings.Replace(fs, "\n", "", -1)
  18. return fs
  19. }
  20. }
  21. func (this *TimeFormatter) ForceTimezone(tz *time.Location) {
  22. this.Printer.UseTimezone(tz)
  23. }
  24. func (this *TimeFormatter) ForceLocalTimezone() {
  25. this.Printer.UseLocalTimezone()
  26. }
  27. func (this *TimeFormatter) ForceUTC() {
  28. this.Printer.UseUTC()
  29. }
  30. func (this *TimeFormatter) ParseFormat(fmtstr string) {
  31. this.Parser.ParseFormatString(&FormatPrinterParsingAbstract{
  32. isEx: false,
  33. tp: this.Printer,
  34. tpe: nil,
  35. }, fmtstr)
  36. }
  37. func NewDefaultTimeFormatter(fmtstr string, multiline bool) *TimeFormatter {
  38. tf := &TimeFormatter{
  39. Printer: NewTimePrinter(),
  40. Multiline: multiline,
  41. Parser: NewFormatParser(false),
  42. }
  43. tf.ParseFormat(fmtstr)
  44. return tf
  45. }
  46. func NewTimeFormatter(printer *TimePrinter, parser *FormatParser, multiline bool) *TimeFormatter {
  47. tf := &TimeFormatter{
  48. Printer: printer,
  49. Multiline: multiline,
  50. Parser: parser,
  51. }
  52. return tf
  53. }