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

2 Answers

0 votes
import java.time.LocalDate

/**
 * Checks if a given year, month, and day are strictly in the future compared to today.
 * Returns true if the date is in the future, false otherwise (or if the date is invalid).
 */
fun isDateInFuture(year: Int, month: Int, day: Int): Boolean {
    return try {
        // 1. Construct the target date safely (throws exception on invalid dates like Feb 30)
        val targetDate = LocalDate.of(year, month, day)

        // 2. Get today's date from the system clock
        val today = LocalDate.now()

        // 3. Compare using the built-in isAfter method
        targetDate.isAfter(today)
    } catch (e: Exception) {
        println("Error: Invalid calendar date provided.")
        false
    }
}

fun main() {
    val testYear = 2035
    val testMonth = 6
    val testDay = 15

    println("Checking date: $testYear-$testMonth-$testDay")

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


/*
run:

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

*/

 



answered 5 hours ago by avibootz
0 votes
import java.util.Calendar

/**
 * Checks if a date is in the future using java.util.Calendar.
 */
fun isDateInFutureCalendar(year: Int, month: Int, day: Int): Boolean {
    // 1. Set up target calendar date
    val targetCal = Calendar.getInstance().apply {
        clear()
        set(year, month - 1, day) // Note: months are 0-indexed in Calendar (0 = January)
    }

    // 2. Set up current calendar date normalized to midnight (00:00:00)
    val todayCal = Calendar.getInstance().apply {
        set(Calendar.HOUR_OF_DAY, 0)
        set(Calendar.MINUTE, 0)
        set(Calendar.SECOND, 0)
        set(Calendar.MILLISECOND, 0)
    }

    // 3. Compare time in milliseconds
    return targetCal.timeInMillis > todayCal.timeInMillis
}

fun main() {
    val testYear = 2035
    val testMonth = 6
    val testDay = 15

    println("Checking date: $testYear-$testMonth-$testDay")

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


/*
run:

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

*/

 



answered 5 hours ago by avibootz
...