Home | | Web Programming | The Time and Date API Added by JDK 8

Chapter: Java The Complete Reference : Introducing GUI Programming with Swing : Introducing Swing

The Time and Date API Added by JDK 8

These new packages define a large number of classes, interfaces, and enumerations that provide extensive, finely grained support for time and date operations.

The Time and Date API Added by JDK 8

 

In Chapter 19, Java’s long-standing approach to handling date and time through the use of classes such as Calendar and GregorianCalendar was discussed. At the time of this writing, this traditional approach is still in widespread use and is something that all Java programmers need to be familiar with. However, with the release of JDK 8, Java now includes another approach to handling time and date. This new approach is defined in the following packages:

Package : Description

                                                                                                                           

java.time : Provides top-level classes that support time and date.

                                                                                                                           

java.time.chrono : Supports alternative, non-Gregorian calendars.

                                                                                                                           

java.time.format : Supports time and date formatting.

                                                                                                                           

java.time.temporal : Supports extended date and time functionality.

                                                                                                                           

java.time.zone : Supports time zones.

 

These new packages define a large number of classes, interfaces, and enumerations that provide extensive, finely grained support for time and date operations. Because of the number of elements that comprise the new time and date API, it can seem fairly intimidating at first. However, it is well organized and logically structured. Its size reflects the detail of control and flexibility that it provides. Although it is far beyond the scope of this book to examine each element in this extensive API, we will look at several of its main classes. As you will see, these classes are sufficient for many uses.

 

Time and Date Fundamentals

 

In java.time are defined several top-level classes that give you easy access to the time and date. Three of these are LocalDate, LocalTime, and LocalDateTime. As their names suggest, they encapsulate the local date, time, and date and time. Using these classes, it is easy to obtain the current date and time, format the date and time, and compare dates and times, among other operations.

LocalDate encapsulates a date that uses the default Gregorian calendar as specified by ISO 8601. LocalTime encapsulates a time, as specified by ISO 8601. LocalDateTime encapsulates both date and time. These classes contain a large number of methods that give you access to the date and time components, allow you to compare dates and times, add or subtract date or time components, and so on. Because a common naming convention for methods is employed, once you know how to use one of these classes, the others are easy to master.

 

 

LocalDate, LocalTime, and LocalDateTime do not define public constructors. Rather, to obtain an instance, you will use a factory method. One very convenient method is now( ), which is defined for all three classes. It returns the current date and/or time of the system. Each class defines several versions, but we will use its simplest form. Here is the version we will use as defined by LocalDate:

 

static LocalDate now( )

 

The version for LocalTime is shown here: static LocalTime now( )

 

The version for LocalDateTime is shown here: static LocalDateTime now( )

As you can see, in each case, an appropriate object is returned. The object returned by now( ) can be displayed in its default, human-readable form by use of a println( ) statement, for example. However, it is also possible to take full control over the formatting of date and time.

 

The following program uses LocalDate and LocalTime to obtain the current date and time and then displays them. Notice how now( ) is called to retrieve the current date and time.

 

 

// A simple example of LocalDate and LocalTime.

import java.time.*;

 

class DateTimeDemo {

 

public static void main(String args[]) {

 

LocalDate curDate = LocalDate.now();

 

System.out.println(curDate);

 

LocalTime curTime = LocalTime.now(); System.out.println(curTime);

 

}

 

}

 

Sample output is shown here:

 

2014-01-01 14:03:41.436

 

The output reflects the default format that is given to the date and time. (The next section shows how to specify a different format.)

Because the preceding program displays both the current date and the current time, it could have been more easily written using the LocalDateTime class. In this approach, only a single instance needs to be created and only a single call to now( ) is required, as shown here:

LocalDateTime curDateTime = LocalDateTime.now();

System.out.println(curDateTime);

Using this approach, the default output includes both date and time. Here is a sample:

 

2014-01-01T14:04:56.799

 

One other point: from a LocalDateTime instance, it is possible to obtain a reference to the date or time component by using the toLocalDate( ) and toLocalTime( ) methods, shown here:

 

LocalDate toLocalDate( ) LocalTime toLocalTime( )

 

Each returns a reference to the indicated element.

 

Formatting Date and Time

 

Although the default formats shown in the preceding examples will be adequate for some uses, often you will want to specify a different format. Fortunately, this is easy to do because

 

LocalDate, LocalTime, and LocalDateTime all provide the format( ) method, shown here:

 

String format(DateTimeFormatter fmtr)

 

Here, fmtr specifies the instance of DateTimeFormatter that will provide the format.

 

DateTimeFormatter is packaged in java.time.format. To obtain a DateTimeFormatter instance, you will typically use one of its factory methods. Three are shown here:

 

static DateTimeFormatter ofLocalizedDate(FormatStyle fmtDate) static DateTimeFormatter ofLocalizedTime(FormatStyle fmtTime)

 

static DateTimeFormatter ofLocalizedDateTime(FormatStyle fmtDate, FormatStyle fmtTime)

Of course, the type of DateTimeFormatter that you create will be based on the type of object it will be operating on. For example, if you want to format the date in a LocalDate instance, then use ofLocalizedDate( ). The specific format is specified by the FormatStyle parameter.

FormatStyle is an enumeration that is packaged in java.time.format. It defines the following constants:

 

FULL

 

LONG

 

MEDIUM

 

SHORT

 

 

These specify the level of detail that will be displayed. (Thus, this form of DateTimeFormatter works similarly to java.text.DateFormat, described earlier in this chapter.)

 

Here is an example that uses DateTimeFormatter to display the current date and time:

 

// Demonstrate DateTimeFormatter.

import java.time.*;

import java.time.format.*;

 

class DateTimeDemo2 {

 

public static void main(String args[]) {

 

LocalDate curDate = LocalDate.now();

 

System.out.println(curDate.format(

 

DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)));

 

LocalTime curTime = LocalTime.now(); System.out.println(curTime.format(

 

DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)));

 

}

 

}

 

Sample output is shown here:

 

Wednesday, January 1, 2014

 

2:16 PM

 

In some situations, you may want a format different from the ones you can specify by use of FormatStyle. One way to accomplish this is to use a predefined formatter, such as ISO_DATE or ISO_TIME, provided by DateTimeFormatter. Another way is to create a custom format by specifying a pattern. To do this, you can use the ofPattern( ) factory method of DateTimeFormatter. One version is shown here:

 

static DateTimeFormatter ofPattern(String fmtPattern)

 

Here, fmtPattern specifies a string that contains the date and time pattern that you want. It returns a DateTimeFormatter that will format according to that pattern. The default locale is used.

 

In general, a pattern consists of format specifiers, called pattern letters. A pattern letter will be replaced by the date or time component that it specifies. The full list of pattern letters is shown in the API documentation for ofPattern( ). Here is a sampling. Note that the pattern letters are case-sensitive.

a : - AM/PM indicator

 : -

d : - Day in month

 : -

E : - Day in week

 : -

h : - Hour, 12-hour clock

 : -

H : - Hour, 24-hour clock

 : -

M : - Month

 : -

m : - Minutes

 : -

s : - Seconds

 : -

y : - Year

 : -

In general, the precise output that you see will be determined by how many times a pattern letter is repeated. (Thus, DateTimeFormatter works a bit like java.text.SimpleDateFormat, described earlier in this chapter.) For example, assuming that the month is April, the patterns:

 

M MM MMM MMMM

 

produce the following formatted output:

 

4 04 Apr April

 

Frankly, experimentation is the best way to understand what each pattern letter does and how various repetitions affect the output.

When you want to output a pattern letter as text, enclose the text between single quotation marks. In general, it is a good idea to enclose all non-pattern characters within single quotation marks to avoid problems if the set of pattern letters changes in subsequent versions of Java.

 

The following program demonstrates the use of a date and time pattern:

 

// Create a custom date and time format.

import java.time.*;

 

import java.time.format.*;

 

class DateTimeDemo3 {

 

public static void main(String args[]) {

 

LocalDateTime curDateTime = LocalDateTime.now(); System.out.println(curDateTime.format(

 

DateTimeFormatter.ofPattern("MMMM d',' yyyy h':'mm a")));

 

}

 

}

 

Sample output is shown here:

 

January 1, 2014 2:22 PM

 

One other point about creating custom date and time output: LocalDate, LocalTime, and LocalDateTime define methods that let you obtain various date and time components. For example, getHour( ) returns the hour as an int; getMonth( ) returns the month in the form of a Month enumeration value; and getYear( ) returns the year as an int. Using these, and other methods, you can manually construct output. You can also use these values for other purposes, such as when creating specialized timers.

Parsing Date and Time Strings

LocalDate, LocalTime, and LocalDateTime provide the ability to parse date and/or time strings. To do this, call parse( ) on an instance of one of those classes. It has two forms. The first uses the default formatter that parses the date and/or time formatted in the standard ISO fashion, such as 03:31 for time and 2014-08-02 for date. The form of this version of parse( ) for LocalDateTime is shown here. (Its form for the other classes is similar except for the type of object returned.)

 

static LocalDateTime parse(CharSequence dateTimeStr)

 

Here, dateTimeStr is a string that contains the date and time in the proper format. If the format is invalid, an error will result.

If you want to parse a date and/or time string that is in a format other than ISO format, you can use a second form of parse( ) that lets you specify your own formatter. The version specified by LocalDateTime is shown next. (The other classes provide a similar form except for the return type.)

 

static LocalDateTime parse(CharSequence dateTimeStr, DateTimeFormatter dateTimeFmtr)

 

Here, dateTimeFmtr specifies the formatter that you want to use.

 

Here is a simple example that parses a date and time string by use of a custom formatter:

 

// Parse a date and time.

import java.time.*;

 

import java.time.format.*;

 

class DateTimeDemo4 {

 

public static void main(String args[]) {

 

// Obtain a LocalDateTime object by parsing a date and time string.

LocalDateTime curDateTime =

LocalDateTime.parse("June 21, 2014 12:01 AM", DateTimeFormatter.ofPattern("MMMM d',' yyyy hh':'mm a"));

 

// Now, display the parsed date and time. System.out.println(curDateTime.format(

 

DateTimeFormatter.ofPattern("MMMM d',' yyyy h':'mm a")));

 

}

 

}

 

Sample output is shown here:

 

June 21, 2014 12:01 AM

 

Other Things to Explore in java.time

 

Although you will want to explore all of the date and time packages, a good place to start is with java.time. It contains a great deal of functionality that you may find useful. Begin by examining the methods defined by LocalDate, LocalTime, and LocalDateTime. Each has methods that let you add or subtract dates and/or times, adjust dates and/or times by a given component, compare dates and/or times, and create instances based on date and/or time components, among others. Other classes in java.time that you may find of particular interest include Instant, Duration, and Period. Instant encapsulates an instant in time. Duration encapsulates a length of time. Period encapsulates a length of date.


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Java The Complete Reference : Introducing GUI Programming with Swing : Introducing Swing : The Time and Date API Added by JDK 8 |


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.