Java Reference
In-Depth Information
Note that by default,
MonthDay
does not return a very useful format. For more
help with formatting, see Recipe 4-17.
How It Works
The Date-Time API includes classes that make it easy to obtain the information that
your application requires for a date. Two of those are the
YearMonth
and
MonthDay
classes. The
YearMonth
class is used to obtain the date in year-month format. It con-
tains a few methods that can be used to obtain the year-month combination. As demon-
strated in the solution, you can call the
now()
method to obtain the current year-
month combination. Similar to the
LocalDate
class,
YearMonth
also contains an
of()
method that accepts a year in
int
format, and an number that represents the
month of the year. In the solution, the
Month enum
is used to obtain the month value.
Similar to the
YearMonth
class,
MonthDay
obtains the date in a month-day
format. It also contains a few different methods for obtaining the month-day combina-
tion. Solution #2 demonstrates two such techniques. Obtaining the current month-day
combination by calling the
now()
method and using the
of()
method to obtain a
month-day combination for a specified date. The
of()
method accepts an
int
value
for the month of the year as its first parameter, and for the second parameter it accepts
an
int
value indicating the day of the month.
4-10. Obtaining and Calculating Based
on the Current Time
Problem
You would like to obtain the current time so that it can be used to stamp a given record.
You would also like to perform calculations on that time.
Solution
Use the
LocalTime
class, which is part of the new Date-Time API, to obtain and dis-
play the current time. In the following lines of code, the
LocalTime
class is demon-
strated.