Java Reference
In-Depth Information
// Convert a number of Seconds since the Epoch, to a local date/time
Instant epochSec
=
Instant
.
ofEpochSecond
(
1000000000L
);
ZoneId zId
=
ZoneId
.
systemDefault
();
ZonedDateTime then
=
ZonedDateTime
.
ofInstant
(
epochSec
,
zId
);
System
.
out
.
println
(
"The epoch was a billion seconds old on "
+
then
);
// Convert a date/time to Epoch seconds
long
long
epochSecond
=
ZonedDateTime
.
now
().
toInstant
().
getEpochSecond
();
System
.
out
.
println
(
"Current epoch seconds = "
+
epochSecond
);
LocalDateTime now
=
LocalDateTime
.
now
();
ZonedDateTime there
=
now
.
atZone
(
ZoneId
.
of
(
"Canada/Pacific"
));
System
.
out
.
printf
(
"When it's %s here, it's %s in Vancouver%n"
,
now
,
there
);
Parsing Strings into Dates
Problem
You need to convert user input into
java.time
objects.
Solution
Use a
parse()
method.
Discussion
Many of the date/time classes have a
parse()
factory method, which tries to parse a string
into an object of that class. For example,
LocalDate.parse(String)
returns a
LocalDate
object for the date given in the input
String
:
/** Show some date parses */
public
public class
class
DateParse
DateParse
{
public
public static
static
void
void
main
(
String
[]
args
) {
String armisticeDate
=
"1914-11-11"
;
LocalDate aLD
=
LocalDate
.
parse
(
armisticeDate
);
System
.
out
.
println
(
"Date: "
+
aLD
);
String armisticeDateTime
=
"1914-11-11T11:11"
;