A presentation I did in IL Java User Group about Java 8, DateTime new features. JSR-310
I wanted it to be informative and a good resource and starting point for this cool feature.
Example – The New Way
12
Today 2014-07-29 and next year 2015-07-29
Modeling
• Different date/time scenarios
• Class starts at 12:30
• ilJUG is on 29th July
• The presentation is 1 hour long
• I’ve been working at eBay for 3 years and 6
months
13
Amount of Time
• How many milliseconds it took
between request to response?
• Set time 10 seconds after now
• Calculate time that passed between
two events
17
Example – Old Calculation
18
now Tue Jul 29 01:48:56 IDT 2014 and later Thu Jan 01 04:20:00 IST 1970
Example – Old Calculation
19
119 days 6 hours 13 minutes 24 seconds 543 ms
Example taken from stackoverflow
Guidelines
• Clear
• Fluent
• DSL
• Immutability
• Amount of time, different
representations for different cases
• Human (year, month, day)
• Machine time
24
Some (not all) Classes
• Temporal – Basic interface for DateTime classes
• LocalDate / LocalTime / LocalDateTime …
• Instant
• Start of nanoseconds in timeline. Useful for timestamp
• Clock
• Allowing Temporal creation with alternate clock
• TemporalAmount – Basic interface for classes
that represent amount of time
• Duration
• Period
26
Methods Naming Conventions
of Static Creates an instance with validation
to Instance Converts to another type (truncate fields)
at Instance Combines this object with another
(expands)
from Static Converts input parameters to an instance
get Instance Part of the state of the object
27
Methods Naming Conventions
is Instance Queries state of an object
with Instance Returns a copy of an object with one
changed element
plus /
minus
instance Returns a copy of an object with amount of
added / subtracted time
parse Static Parses input string to an instance
format Instance Uses formatter to format the object’s values
to produce a string
28
Instant
41
From Javadoc:
"This class models a single instantaneous point on the time-line.
This might be used to record event time-stamps in the application...
"...number of seconds that can be held in a long. This is greater than the current
estimated age of the universe...
"...The instant is stored to nanosecond resolution..."
Adjusters
• Take Temporal value and adjust it
• Pre defined
• firstDayOfMonth
• firstDayOfYear
• lastInMonth
• Look at TemoralAdjusters
• Custom adjusters
42
Parsing and Formatting
• DateTimeFormatter
• Many pre defined formats
• http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#predefined
• Immutable
• DateTimeFormatterBuilder
• All classes use the same way
• DateTimeParseException (runtime)
48