Class DateTimeApiExamples
java.lang.Object
net.jrodolfo.java_evolution.java08.DateTimeApiExamples
Demonstrates the Date and Time API introduced in Java 8 under
java.time.
Before Java 8, date and time code usually relied on java.util.Date,
java.util.Calendar, and java.text.SimpleDateFormat. Those
APIs mixed different concepts, were mutable, and made time-zone handling
difficult to reason about.
The Java 8 API solves this by giving different time concepts different
immutable types. LocalDate represents a date without a time zone,
LocalDateTime represents a local date and time, ZonedDateTime
adds a zone, Period represents date-based amounts, and
Duration represents time-based amounts. The clearer types make many
bugs visible in the method signature.
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionAdds days to a date, returning a new instance because java.time types are immutable.createLocalDate(int year, int month, int day) Creates a date without a time zone.createZonedDateTime(LocalDateTime dateTime, String zoneId) Creates a date-time associated with a time zone.durationBetween(LocalDateTime start, LocalDateTime end) Calculates a time-based amount of time withDuration.formatIsoDate(LocalDate date) Formats a date withDateTimeFormatter.parseBrazilianDate(String text) Parses a date using an explicit formatter.periodBetween(LocalDate start, LocalDate end) Calculates a date-based amount of time withPeriod.
-
Constructor Details
-
DateTimeApiExamples
public DateTimeApiExamples()
-
-
Method Details
-
createLocalDate
Creates a date without a time zone.- Parameters:
year- the yearmonth- the month from 1 to 12day- the day of the month- Returns:
- the requested local date
-
addDays
-
periodBetween
-
durationBetween
Calculates a time-based amount of time withDuration.- Parameters:
start- the start date-timeend- the end date-time- Returns:
- the duration between both date-times
-
formatIsoDate
Formats a date withDateTimeFormatter.- Parameters:
date- the date to format- Returns:
- the date formatted as
yyyy-MM-dd
-
parseBrazilianDate
-
createZonedDateTime
Creates a date-time associated with a time zone.- Parameters:
dateTime- the local date-timezoneId- the zone identifier, such asAmerica/Sao_Paulo- Returns:
- the zoned date-time
-