You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

timestamp.go 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package timeutil
  5. import (
  6. "time"
  7. "code.gitea.io/gitea/modules/setting"
  8. )
  9. // TimeStamp defines a timestamp
  10. type TimeStamp int64
  11. // TimeStampNow returns now int64
  12. func TimeStampNow() TimeStamp {
  13. return TimeStamp(time.Now().Unix())
  14. }
  15. // Add adds seconds and return sum
  16. func (ts TimeStamp) Add(seconds int64) TimeStamp {
  17. return ts + TimeStamp(seconds)
  18. }
  19. // AddDuration adds time.Duration and return sum
  20. func (ts TimeStamp) AddDuration(interval time.Duration) TimeStamp {
  21. return ts + TimeStamp(interval/time.Second)
  22. }
  23. // Year returns the time's year
  24. func (ts TimeStamp) Year() int {
  25. return ts.AsTime().Year()
  26. }
  27. // AsTime convert timestamp as time.Time in Local locale
  28. func (ts TimeStamp) AsTime() (tm time.Time) {
  29. return ts.AsTimeInLocation(setting.DefaultUILocation)
  30. }
  31. // AsTimeInLocation convert timestamp as time.Time in Local locale
  32. func (ts TimeStamp) AsTimeInLocation(loc *time.Location) (tm time.Time) {
  33. tm = time.Unix(int64(ts), 0).In(loc)
  34. return
  35. }
  36. // AsTimePtr convert timestamp as *time.Time in Local locale
  37. func (ts TimeStamp) AsTimePtr() *time.Time {
  38. return ts.AsTimePtrInLocation(setting.DefaultUILocation)
  39. }
  40. // AsTimePtrInLocation convert timestamp as *time.Time in customize location
  41. func (ts TimeStamp) AsTimePtrInLocation(loc *time.Location) *time.Time {
  42. tm := time.Unix(int64(ts), 0).In(loc)
  43. return &tm
  44. }
  45. // Format formats timestamp as given format
  46. func (ts TimeStamp) Format(f string) string {
  47. return ts.FormatInLocation(f, setting.DefaultUILocation)
  48. }
  49. // FormatInLocation formats timestamp as given format with spiecific location
  50. func (ts TimeStamp) FormatInLocation(f string, loc *time.Location) string {
  51. return ts.AsTimeInLocation(loc).Format(f)
  52. }
  53. // FormatLong formats as RFC1123Z
  54. func (ts TimeStamp) FormatLong() string {
  55. return ts.Format(time.RFC1123Z)
  56. }
  57. // FormatShort formats as short
  58. func (ts TimeStamp) FormatShort() string {
  59. return ts.Format("Jan 02, 2006")
  60. }
  61. // IsZero is zero time
  62. func (ts TimeStamp) IsZero() bool {
  63. return ts.AsTimeInLocation(time.Local).IsZero()
  64. }