summaryrefslogtreecommitdiff
path: root/humanFormat.go
blob: cf1f907352534c84b36f6ce7cc1b6abf12de7faf (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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package config

import (
	"fmt"
	"time"
)

// This isn't for the marketing department
// so this isn't going to use 'MiB' and 'GiB'
func HumanFormatBytes(b int) string {
	if b < 2000 {
		return fmt.Sprintf("%d B", b)
	}

	kb := int(b / 1024)
	if kb < 2000 {
		return fmt.Sprintf("%d KB", kb)
	}

	mb := int(b / (1024 * 1024))
	if mb < 2000 {
		return fmt.Sprintf("%d MB", mb)
	}

	gb := int(b / (1024 * 1024 * 1024))
	if gb < 2000 {
		return fmt.Sprintf("%d GB", gb)
	}

	tb := int(b / (1024 * 1024 * 1024 * 1024))
	return fmt.Sprintf("%d TB", tb)
}

func FormatDuration(d time.Duration) string {
	result := ""

	// check if it's more than a year
	years := int(d.Hours()) / (24 * 365)
	if years > 0 {
		result += fmt.Sprintf("%dy", years)
		return result
	}

	// check if it's more than a day
	days := int(d.Hours()) / 24
	if days > 0 {
		result += fmt.Sprintf("%dd", days)
		return result
	}

	// check if it's more than an hour
	hours := int(d.Hours()) % 24
	if hours > 0 {
		result += fmt.Sprintf("%dh", hours)
		return result
	}

	// check if it's more than a minute
	minutes := int(d.Minutes()) % 60
	if minutes > 0 {
		result += fmt.Sprintf("%dm", minutes)
		return result
	}

	// check if it's more than a second
	seconds := int(d.Seconds()) % 60
	if seconds > 0 {
		result += fmt.Sprintf("%ds", seconds)
		return result
	}

	// report in milliseconds
	ms := int(d.Milliseconds())
	if ms > 100 {
		// todo: print .3s, etc ?
		return fmt.Sprintf("%1.2fs", float64(seconds)/1000)
	}
	if ms > 0 {
		result += fmt.Sprintf("%dms", ms)
	}

	// totally not necessary but wth
	var t time.Duration
	t = time.Duration(ms) * time.Millisecond
	nanos := d - t
	result += fmt.Sprintf("%dnanos", nanos)
	return result
}