File: date.go

package info (click to toggle)
lazygit 0.50.0%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,808 kB
  • sloc: sh: 128; makefile: 76
file content (67 lines) | stat: -rw-r--r-- 1,462 bytes parent folder | download | duplicates (2)
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
package utils

import (
	"fmt"
	"time"
)

func UnixToTimeAgo(timestamp int64) string {
	now := time.Now().Unix()
	return formatSecondsAgo(now - timestamp)
}

const (
	SECONDS_IN_SECOND = 1
	SECONDS_IN_MINUTE = 60
	SECONDS_IN_HOUR   = 3600
	SECONDS_IN_DAY    = 86400
	SECONDS_IN_WEEK   = 604800
	SECONDS_IN_YEAR   = 31536000
	SECONDS_IN_MONTH  = SECONDS_IN_YEAR / 12
)

type period struct {
	label           string
	secondsInPeriod int64
}

var periods = []period{
	{"s", SECONDS_IN_SECOND},
	{"m", SECONDS_IN_MINUTE},
	{"h", SECONDS_IN_HOUR},
	{"d", SECONDS_IN_DAY},
	{"w", SECONDS_IN_WEEK},
	{"M", SECONDS_IN_MONTH},
	{"y", SECONDS_IN_YEAR},
}

func formatSecondsAgo(secondsAgo int64) string {
	for i, period := range periods {
		if i == 0 {
			continue
		}

		if secondsAgo < period.secondsInPeriod {
			return fmt.Sprintf("%d%s",
				secondsAgo/periods[i-1].secondsInPeriod,
				periods[i-1].label,
			)
		}
	}

	return fmt.Sprintf("%d%s",
		secondsAgo/periods[len(periods)-1].secondsInPeriod,
		periods[len(periods)-1].label,
	)
}

// formats the date in a smart way, if the date is today, it will show the time, otherwise it will show the date
func UnixToDateSmart(now time.Time, timestamp int64, longTimeFormat string, shortTimeFormat string) string {
	date := time.Unix(timestamp, 0)

	if date.Day() == now.Day() && date.Month() == now.Month() && date.Year() == now.Year() {
		return date.Format(shortTimeFormat)
	}

	return date.Format(longTimeFormat)
}