Last active
July 23, 2024 13:42
-
-
Save ayoisaiah/b8d1b880c7ffb36189a36358f09f0285 to your computer and use it in GitHub Desktop.
Countdown timer in Golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Tutorial: https://freshman.tech/golang-timer/ | |
package main | |
import ( | |
"flag" | |
"fmt" | |
"os" | |
"time" | |
) | |
func main() { | |
deadline := flag.String("deadline", "", "The deadline for the countdown timer in RFC3339 format (e.g. 2019-12-25T15:00:00+01:00)") | |
flag.Parse() | |
if *deadline == "" { | |
flag.PrintDefaults() | |
os.Exit(1) | |
} | |
v, err := time.Parse(time.RFC3339, *deadline) | |
if err != nil { | |
fmt.Println(err) | |
os.Exit(1) | |
} | |
for range time.Tick(1 * time.Second) { | |
timeRemaining := getTimeRemaining(v) | |
if timeRemaining.t <= 0 { | |
fmt.Println("Countdown reached!") | |
break | |
} | |
fmt.Printf("Days: %d Hours: %d Minutes: %d Seconds: %d\n", timeRemaining.d, timeRemaining.h, timeRemaining.m, timeRemaining.s) | |
} | |
} | |
type countdown struct { | |
t int | |
d int | |
h int | |
m int | |
s int | |
} | |
func getTimeRemaining(t time.Time) countdown { | |
currentTime := time.Now() | |
difference := t.Sub(currentTime) | |
total := int(difference.Seconds()) | |
days := int(total / (60 * 60 * 24)) | |
hours := int(total / (60 * 60) % 24) | |
minutes := int(total/60) % 60 | |
seconds := int(total % 60) | |
return countdown{ | |
t: total, | |
d: days, | |
h: hours, | |
m: minutes, | |
s: seconds, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment