Skip to content

Instantly share code, notes, and snippets.

@ayoisaiah
Last active August 8, 2022 13:26
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ayoisaiah/b8d1b880c7ffb36189a36358f09f0285 to your computer and use it in GitHub Desktop.
Save ayoisaiah/b8d1b880c7ffb36189a36358f09f0285 to your computer and use it in GitHub Desktop.
Countdown timer in Golang
// 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