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

2 Answers

0 votes
import java.time.LocalDate
import scala.util.Try

object FutureDateChecker {

  /** 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).
    */
  def isDateInFuture(year: Int, month: Int, day: Int): Boolean = {
    // 1. Safely construct the target date (Try catches invalid dates like Feb 30)
    val targetDateTry = Try(LocalDate.of(year, month, day))

    targetDateTry match {
      case scala.util.Success(targetDate) =>
        // 2. Get today's date from the system clock
        val today = LocalDate.now()
        
        // 3. Compare using the built-in isAfter method
        targetDate.isAfter(today)
        
      case scala.util.Failure(_) =>
        System.err.println("Error: Invalid calendar date provided.")
        false
    }
  }

  def main(args: Array[String]): Unit = {
    val testYear = 2035
    val testMonth = 6
    val testDay = 15

    println(s"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

object FutureDateCheckerLegacy {

  /** Checks if a date is in the future using java.util.Calendar.
    */
  def isDateInFutureLegacy(year: Int, month: Int, day: Int): Boolean = {
    // 1. Set up target calendar date
    val targetCal = Calendar.getInstance()
    targetCal.clear()
    targetCal.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()
    todayCal.set(Calendar.HOUR_OF_DAY, 0)
    todayCal.set(Calendar.MINUTE, 0)
    todayCal.set(Calendar.SECOND, 0)
    todayCal.set(Calendar.MILLISECOND, 0)

    // 3. Compare time in milliseconds
    targetCal.getTimeInMillis > todayCal.getTimeInMillis
  }

  def main(args: Array[String]): Unit = {
    val testYear = 2035
    val testMonth = 6
    val testDay = 15

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

    if (isDateInFutureLegacy(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
...