In the previous versions of Java , date and time functionality was implemented using the types defined in the java.util. For example to work with dates there is a java.util.Date type.
Below is a sample code to print the current date
Date date = new Date(); System.out.println(date.toString());
Output
Tue Dec 15 19:42:35 IST 2015
There are few limitations with the date and time types defined in the java.util package.
- There is no way to work with only time or only with dates.Since time and date both are represented by the same type Date.
- Methods are not consistent. For example when calling different methods we get some unexpected values.Assume Current date is “15 Dec 2015 ”
Method Return value date.getDay() 2 date.getYear() 115 date.getMonth() 11
As we can see the values returned by the different methods is not what we expected.getDay() returns 2 ,which is the second day of the week.getYear() returns 115 while the current year is 2015.getMonth() returns 11 while the current month is 12.
- Date and Time classes defined in the java.util package are not thread safe.
The Date-Time API provided in Java 8 provides the solution to the problems in the legacy Date-Time API.
It consists of different types for working with date and time values.To create objects of these types we use factory methods instead of constructors.
Following are some of the main classes in the Date and Time API in Java 8.
Type | Use |
LocalDate | Represents a date value without a time-zone |
LocalTime | Represents a time value without a time-zone |
LocalDateTime | Represents a date-time value without a time-zone |
Year | Represents a year |
YearMonth | Represents an year and a month |
MonthDay | Represents a combination of month and day |
ZonedDateTime | Represents a date-time with a time-zone |
The types are defined in the package java.time.To get the date time values we can use the below code. now() method returns the current date or time value.
import java.time.LocalDate; import java.time.LocalTime; public class DateTimeApplication{ public static void main(String []args) throws IOException { LocalDate date = LocalDate.now(); LocalTime time = LocalTime.now(); int year= date.getYear(); MonthDay monthDay = MonthDay.now(); YearMonth yearMonth=YearMonth.now(); System.out.println(date); System.out.println(time); System.out.println(year); System.out.println(monthDay); System.out.println(yearMonth); } }
output:
2015-12-15
23:16:41.653
2015
–12-15
2015-12
We can also create objects of these types by specifying values rather using the now() method which returns the current date time value.To do so we use of() methods defined by these types:
LocalDate date=LocalDate.of(2015, 12, 15); LocalTime time = LocalTime.of(10,15);
output:
2015-12-15
10:15
Leave a Reply