How to check if a date is in the future with Go

2 Answers

0 votes
package main

import (
	"fmt"
	"time"
)

// IsDateInFuture checks if the given year, month, and day are strictly in the future.
// It normalizes both dates to midnight (00:00:00 UTC) for a pure calendar day comparison.
func IsDateInFuture(year int, month time.Month, day int) bool {
	// 1. Construct the target date at midnight UTC
	target := time.Date(year, month, day, 0, 0, 0, 0, time.UTC)

	// 2. Get current time in UTC and truncate/normalize to midnight
	now := time.Now().UTC()
	today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)

	// 3. Compare dates using the After method
	return target.After(today)
}

func main() {
	// Example test values
	testYear := 2035
	testMonth := time.June
	testDay := 15

	fmt.Printf("Checking date: %04d-%02d-%02d\n", testYear, testMonth, testDay)

	if IsDateInFuture(testYear, testMonth, testDay) {
		fmt.Println("Result: The date is in the FUTURE.")
	} else {
		fmt.Println("Result: The date is NOT in the future.")
	}
}


/*
run:

Checking date: 2035-06-15
Result: The date is in the FUTURE.

*/

 



answered 40 minutes ago by avibootz
0 votes
package main

import (
	"fmt"
	"time"
)

// IsDateInFutureString checks if a target date string ("YYYY-MM-DD") is in the future.
// Leverages lexicographical string sorting inherent to the ISO-8601 standard format.
func IsDateInFutureString(dateStr string) (bool, error) {
	// 1. Validate that the input string is a valid date format
	_, err := time.Parse("2006-01-02", dateStr)
	if err != nil {
		return false, err
	}

	// 2. Format today's date as "YYYY-MM-DD" in local time
	todayStr := time.Now().Format("2006-01-02")

	// 3. Direct lexicographical string comparison
	return dateStr > todayStr, nil
}

func main() {
	testDate := "2035-06-15"

	fmt.Printf("Checking date: %s\n", testDate)

	isFuture, err := IsDateInFutureString(testDate)
	if err != nil {
		fmt.Printf("Error parsing date: %v\n", err)
		return
	}

	if isFuture {
		fmt.Println("Result: The date is in the FUTURE.")
	} else {
		fmt.Println("Result: The date is NOT in the future.")
	}
}


/*
run:

Checking date: 2035-06-15
Result: The date is in the FUTURE.

*/

 



answered 26 minutes ago by avibootz
...