How to calculate the number of days until Christmas from today in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "time"
)

// ---------------------------------------------------------
// Function: daysUntilChristmas
// Purpose : Calculate how many days remain until Christmas.
// ---------------------------------------------------------
func daysUntilChristmas() int {
    // Get today's date from the system
    today := time.Now()

    // Extract the current year
    year := today.Year()

    // Build a date for Christmas of the current year
    // December = month 12 (Go uses 1–12)
    christmas := time.Date(year, time.December, 25, 0, 0, 0, 0, today.Location())

    // If Christmas already passed this year, calculate for next year
    if today.After(christmas) {
        christmas = time.Date(year+1, time.December, 25, 0, 0, 0, 0, today.Location())
    }

    // Calculate difference in days between today and Christmas
    diff := christmas.Sub(today)
    days := int(diff.Hours() / 24)

    return days
}

func main() {
    days := daysUntilChristmas()
    
    fmt.Println("Days until Christmas:", days)
}


/*
run:

Days until Christmas: 209

*/

 



answered May 29 by avibootz
...