Search code examples
javascaladatedeprecateddesign-decisions

Why was getMonth deprecated on java.sql.Date and java.util.Date


I should preface this with I use Apache Spark, which uses java.sql.Date, in case anyone suggests I should use dates from java.time. The example below is in Scala.

The API that I use (which is deprecated) to get the month for a date is as follows:

val date: java.sql.Date = ???
val month = date.getMonth()

However if I look at how it appears I should do this based on the deprecation, the above code would be re-written as follows:

val date: java.sql.Date = ???
val cal = Calendar.getInstance()
cal.setTime(date)
cal.get(Calendar.MONTH)

The simplicity and readability of the code is significantly different, and the date being a side effect on the calendar is not terribly nice from a functional programming point of view. Can someone explain why they think this change was made?


Solution

  • Prior to JDK 1.1, the class Date had two additional functions. It allowed the interpretation of dates as year, month, day, hour, minute, and second values. It also allowed the formatting and parsing of date strings. Unfortunately, the API for these functions was not amenable to internationalization. As of JDK 1.1, the Calendar class should be used to convert between dates and time fields and the DateFormat class should be used to format and parse date strings. The corresponding methods in Date are deprecated.

    The JavaDoc explains. Internationalization.


    "in case anyone suggests I should use dates from java.time"

    There is nothing to stop you from converting to java.time classes as soon as possible, performing whatever calculations/modifications you need and, if you need to re-insert, converting back to java.sql.Date again.