aboutsummaryrefslogtreecommitdiffhomepage
path: root/template/elapsed.go
blob: bfcc3eefa92ecfc7ab61e18931ed06ea5bd703dd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// 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 // import "miniflux.app/template"

import (
	"math"
	"time"

	"miniflux.app/locale"
	"miniflux.app/timezone"
)

// 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`
)

// ElapsedTime returns in a human readable format the elapsed time
// since the given datetime.
func elapsedTime(language *locale.Language, tz string, t time.Time) string {
	if t.IsZero() {
		return language.Get(NotYet)
	}

	now := timezone.Now(tz)
	t = timezone.Convert(tz, t)
	if now.Before(t) {
		return language.Get(NotYet)
	}

	diff := now.Sub(t)
	// Duration in seconds
	s := diff.Seconds()
	// Duration in days
	d := int(s / 86400)
	switch {
	case s < 60:
		return language.Get(JustNow)
	case s < 120:
		return language.Get(LastMinute)
	case s < 3600:
		return language.Get(Minutes, int(diff.Minutes()))
	case s < 7200:
		return language.Get(LastHour)
	case s < 86400:
		return language.Get(Hours, int(diff.Hours()))
	case d == 1:
		return language.Get(Yesterday)
	case d < 7:
		return language.Get(Days, d)
	case d < 31:
		return language.Get(Weeks, int(math.Ceil(float64(d)/7)))
	case d < 365:
		return language.Get(Months, int(math.Ceil(float64(d)/30)))
	default:
		return language.Get(Years, int(math.Ceil(float64(d)/365)))
	}
}