Let’s face it, even if you are a first-time Java Enthusiast, even if you love this language as much as I do, the handling of java.util.Date and java.sql.Date objects has never sat well with you, has it? You even convinced yourself, over time, that having a single object to manage date and time was all in all convenient! And patience for those deprecated methods (or you used the Joda-Time library…), well, that was true in 1998, yes the last century, that’s right, because little or nothing has changed since then. Take a look at the source code of the java.util.Date class.
* @author James Gosling
* @author Arthur van Hoff
* @author Alan Liu
* @see java.text.DateFormat
* @see java.util.Calendar
* @see java.util.TimeZone
* @since JDK1.0
*/
public class Date implements java.io.Serializable, Cloneable, Comparable<Date> {
Have you noticed @since JDK1.0
?
And what about those deprecated constuctors that are so convenient:
* @param year the year minus 1900.
* @param month the month between 0-11.
* @param date the day of the month between 1-31.
* @see java.util.Calendar
* @deprecated As of JDK version 1.1,
* replaced by <code>Calendar.set(year + 1900, month, date)</code>
* or <code>GregorianCalendar(year + 1900, month, date)</code>.
*/
@Deprecated
public Date(int year, int month, int date) {
this(year, month, date, 0, 0, 0);
}
Note @deprecated As of JDK version 1.1
Not to mention methods like getYear()
, fantastic! What if. “oh! tomorrow we go into production, let’s not play games!
you can’t touch the code that’s running! deprecated methods will bury us all anyway, just imagine, Oracle won’t remove them until 2030.”
* @deprecated As of JDK version 1.1,
* replaced by <code>Calendar.get(Calendar.YEAR) - 1900</code>.
*/
@Deprecated
public int getYear() {
return normalize().getYear() - 1900;
}
Yes, maybe you are right (you thought so too, don’t deny it). Now though, if there was something better that make your life easier, wouldn’t you use it?
Well, the first impression with LocalTime and LocalDate was not great, they could do something more, for example make more immediate to switch from the old Date objects to the new LocalDate and LocalTime, but if you think about it, maybe it’s better that way, new design, just LocalDate and LocalTime objects.
For today, let’s start with something very basic, but which we often do
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
passing from a textual representation (HH:mm) to a LocalTime object, and vice versa. Below is the code.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
LocalTime localTime1 = LocalTime.now();
String localTime1AsString = formatter.format(localTime1);
System.out.println("localTime1AsString:"+localTime1AsString);
//From String HH:mm To LocalTime object (parsing)
LocalTime lTime = LocalTime.parse("23:59",formatter);
System.out.println("lTime.toString()"+lTime.toString());