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 convenient! Joda-Time was a common alternative because little or nothing has changed since the last century. 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 constructors 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 the @deprecated tag as of JDK version 1.1:
…
Not to mention methods like getYear(). Imagine if someone said: “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; 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, if there was something better to make your life easier, wouldn’t you use it?
For today, let’s start with something very basic, but frequently used:
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
The following code demonstrates converting between a textual representation (HH:mm) and a LocalTime object:
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());
