miniflux/template/elapsed.go

71 lines
1.6 KiB
Go
Raw Normal View History

2017-11-20 06:10:04 +01:00
// Copyright (c) 2017 Hervé Gouchet. All rights reserved.
// Use of this source code is governed by the MIT License
// that can be found in the LICENSE file.
package template
2017-11-20 06:10:04 +01:00
import (
"math"
"time"
2017-12-13 06:48:13 +01:00
"github.com/miniflux/miniflux/locale"
"github.com/miniflux/miniflux/timezone"
2017-11-20 06:10:04 +01:00
)
// Texts to be translated if necessary.
var (
NotYet = `not yet`
JustNow = `just now`
LastMinute = `1 minute ago`
Minutes = `%d minutes ago`
LastHour = `1 hour ago`
Hours = `%d hours ago`
Yesterday = `yesterday`
Days = `%d days ago`
Weeks = `%d weeks ago`
Months = `%d months ago`
Years = `%d years ago`
)
2018-01-03 04:15:08 +01:00
// ElapsedTime returns in a human readable format the elapsed time
2017-11-20 06:10:04 +01:00
// since the given datetime.
func elapsedTime(language *locale.Language, tz string, t time.Time) string {
if t.IsZero() {
return language.Get(NotYet)
2017-11-20 06:10:04 +01:00
}
now := timezone.Now(tz)
t = timezone.Convert(tz, t)
if now.Before(t) {
return language.Get(NotYet)
}
diff := now.Sub(t)
2017-11-20 06:10:04 +01:00
// Duration in seconds
s := diff.Seconds()
// Duration in days
d := int(s / 86400)
switch {
case s < 60:
return language.Get(JustNow)
2017-11-20 06:10:04 +01:00
case s < 120:
return language.Get(LastMinute)
2017-11-20 06:10:04 +01:00
case s < 3600:
return language.Get(Minutes, int(diff.Minutes()))
2017-11-20 06:10:04 +01:00
case s < 7200:
return language.Get(LastHour)
2017-11-20 06:10:04 +01:00
case s < 86400:
return language.Get(Hours, int(diff.Hours()))
2017-11-20 06:10:04 +01:00
case d == 1:
return language.Get(Yesterday)
2017-11-20 06:10:04 +01:00
case d < 7:
return language.Get(Days, d)
2017-11-20 06:10:04 +01:00
case d < 31:
return language.Get(Weeks, int(math.Ceil(float64(d)/7)))
2017-11-20 06:10:04 +01:00
case d < 365:
return language.Get(Months, int(math.Ceil(float64(d)/30)))
2017-11-20 06:10:04 +01:00
default:
return language.Get(Years, int(math.Ceil(float64(d)/365)))
2017-11-20 06:10:04 +01:00
}
}