Java Reference
In-Depth Information
public
public class
class
CurrentDateTime
CurrentDateTime
{
public
public static
void
main
(
String
[]
args
) {
LocalDate dNow
=
LocalDate
.
now
();
System
.
out
.
println
(
dNow
);
LocalTime tNow
=
LocalTime
.
now
();
System
.
out
.
println
(
tNow
);
LocalDateTime now
=
LocalDateTime
.
now
();
System
.
out
.
println
(
now
);
static
void
}
}
Running it produces this output:
2013-10-28
22:23:55.641
2013-10-28T22:23:55.642
The formatting is nothing spectacular, but it's adequate. We'll deal with fancier formatting in
the next recipe,
Formatting Dates and Times
.
Formatting Dates and Times
Problem
You want to provide better formatting for date and time objects.
Solution
Use
java.time.format.DateTimeFormatter
.
Discussion
The
DateTimeFormatter
class provides an amazing number of possible formatting styles. If
you don't want to use one of the provided 20 or so predefined formats, you can define your
own using
DateTimeFormatter.ofPattern(String pattern)
. The “pattern” string can
contain any characters, but almost every letter of the alphabet has been defined to mean
something, in addition to the obvious Y, M, D, h, m, and s. In addition, the quote character