-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcountdown.go
More file actions
99 lines (78 loc) · 1.66 KB
/
countdown.go
File metadata and controls
99 lines (78 loc) · 1.66 KB
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
89
90
91
92
93
94
95
96
97
98
99
package main
import (
"fmt"
"os"
"strings"
"time"
)
var (
formats = []string{
"2006-01-02",
"Monday",
"2/1",
"15:04",
time.Kitchen,
time.RFC1123,
time.RFC1123Z,
time.RFC3339,
time.RFC3339Nano,
time.RFC822,
time.RFC822Z,
time.RFC850,
}
)
func main() {
var target time.Time
input := os.Args[1]
d, err := time.ParseDuration(input)
if err == nil {
target = time.Now().Add(-d)
}
for _, format := range formats {
t, err := time.Parse(format, input)
if err == nil {
target = t
break
}
}
if target.Unix() == new(time.Time).Unix() {
fmt.Printf("Could not parse date: %q\n", input)
os.Exit(1)
}
fmt.Println(target)
// Assume year was not given and add the target to current time.
if target.Year() == 0 {
epoch := time.Now().Truncate(24 * time.Hour)
diff := target.Sub(epoch)
fmt.Println(diff)
target = time.Now().Add(diff)
}
fmt.Println(target)
for {
diff := target.Sub(time.Now())
days := int(diff.Hours() / 24)
hours := int(diff.Hours()) % 24
minutes := int(diff.Minutes()) % 60
seconds := int(diff.Minutes()*60) % 60
postfix := "left"
scale := 1
if target.Before(time.Now()) {
postfix = "ago"
scale = -1
}
var parts []string
if diff.Hours() > 24 {
parts = append(parts, fmt.Sprintf("%v days", scale*days))
}
if diff.Hours() > 0 {
parts = append(parts, fmt.Sprintf("%v hours", scale*hours))
}
if diff.Minutes() > 0 {
parts = append(parts, fmt.Sprintf("%v minutes", scale*minutes))
}
parts = append(parts, fmt.Sprintf("%v seconds", scale*seconds))
parts = append(parts, postfix)
fmt.Printf("\r%v", strings.Join(parts, " "))
time.Sleep(1 * time.Second)
}
}