extension.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package strftime
  2. import (
  3. "strconv"
  4. "time"
  5. )
  6. // NOTE: declare private variable and iniitalize once in init(),
  7. // and leave the Milliseconds() function as returning static content.
  8. // This way, `go doc -all` does not show the contents of the
  9. // milliseconds function
  10. var milliseconds Appender
  11. var microseconds Appender
  12. var unixseconds Appender
  13. func init() {
  14. milliseconds = AppendFunc(func(b []byte, t time.Time) []byte {
  15. millisecond := int(t.Nanosecond()) / int(time.Millisecond)
  16. if millisecond < 100 {
  17. b = append(b, '0')
  18. }
  19. if millisecond < 10 {
  20. b = append(b, '0')
  21. }
  22. return append(b, strconv.Itoa(millisecond)...)
  23. })
  24. microseconds = AppendFunc(func(b []byte, t time.Time) []byte {
  25. microsecond := int(t.Nanosecond()) / int(time.Microsecond)
  26. if microsecond < 100000 {
  27. b = append(b, '0')
  28. }
  29. if microsecond < 10000 {
  30. b = append(b, '0')
  31. }
  32. if microsecond < 1000 {
  33. b = append(b, '0')
  34. }
  35. if microsecond < 100 {
  36. b = append(b, '0')
  37. }
  38. if microsecond < 10 {
  39. b = append(b, '0')
  40. }
  41. return append(b, strconv.Itoa(microsecond)...)
  42. })
  43. unixseconds = AppendFunc(func(b []byte, t time.Time) []byte {
  44. return append(b, strconv.FormatInt(t.Unix(), 10)...)
  45. })
  46. }
  47. // Milliseconds returns the Appender suitable for creating a zero-padded,
  48. // 3-digit millisecond textual representation.
  49. func Milliseconds() Appender {
  50. return milliseconds
  51. }
  52. // Microsecond returns the Appender suitable for creating a zero-padded,
  53. // 6-digit microsecond textual representation.
  54. func Microseconds() Appender {
  55. return microseconds
  56. }
  57. // UnixSeconds returns the Appender suitable for creating
  58. // unix timestamp textual representation.
  59. func UnixSeconds() Appender {
  60. return unixseconds
  61. }