SlideShare a Scribd company logo
Sualeh Fatehi
Java 8 Date and
Time API
This work by Sualeh Fatehi is licensed under
a Creative Commons Attribution-
NonCommercial 4.0 International License.
 Review the current date and time API
 Understand date and time concepts
 Take a look at the new date and time API
Overview
Several problems here:
1. Which 12 is for which date field?
2. Month 12 is December, right? No. January.
3. Year 12 is 12 CE, right? Wrong. 1913.
4. Wait - there is a time in a date?
5. More than that, there is a time zone.
Problems Getting a Date
System.out.println(new Date(12, 12, 12));
// Sun Jan 12 00:00:00 EST 1913
 Conceptually an instant, not a date
 Properties have random offsets
 Some zero-based, like month and hours
 Some one-based, like day of the month
 Year has an offset of 1900
 Mutable, not thread-safe
 Not internationalizable
 Millisecond granularity
 Does not reflect UTC
A Sorry Implementation
 Date was the work of James Gosling and
Arthur van Hoff
 Added in JDK 1.0, mostly deprecated in
JDK 1.1, never removed
 IBM donated Calendar code to Sun
Back Story
System.out.println(new
GregorianCalendar(12, 12, 12));
Revisited Examples
java.util.GregorianCalendar[time=?,areFieldsSet=false,areA
llFieldsSet=false,lenient=true,zone=sun.util.calendar.Zone
Info[id="America/New_York",offset=-
18000000,dstSavings=3600000,useDaylight=true,transitions=2
35,lastRule=java.util.Simpletime
zone[id=America/New_York,offset=-
18000000,dstSavings=3600000,useDaylight=true,startYear=0,s
tartMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startT
ime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1
,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOf
Week=1,minimalDaysInFirstWeek=1,ERA=?,YEAR=12,MONTH=12,WEE
K_OF_YEAR=?,WEEK_OF_MONTH=?,DAY_OF_MONTH=12,DAY_OF_YEAR=?,
DAY_OF_WEEK=?,DAY_OF_WEEK_IN_MONTH=?,AM_PM=0,HOUR=0,HOUR_O
F_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=?,ZONE_OFFSET=?,DST_
OFFSET=?]
Several problems here:
1. Which 12 is for which date field?
2. Month 12 is December, right? No. January.
3. They got the year right! Almost. 13 CE.
4. Wait - there is a time in a calendar?
5. More than that, there is a time zone.
Problems Getting a Date
System.out.println(dtFmt.format(new
GregorianCalendar(12,12,12).getTime()));
// January 12, 0013 12:00:00 AM EST
 “Calendar” represents a date, time and
time-zone
 Defaults to Gregorian calendar
 In Thailand only, you get a Buddhist
calendar
 You can ask specifically ask for a Japanese
calendar
Calendar
 Conceptually an instant, not a calendar
 But, can’t create a Calendar from a Date
 Can’t format a Calendar
 Zero-based offsets
 Stores internal state in two different ways
 milliseconds from epoch
 set of fields
 Has bugs and performance issues
 Mutable, not thread-safe
Not Much Improvement
 2002 - Stephen Colebourne starts open
source Joda-Time project
 2005 - Release of Joda-Time 1.0
 2007 - JSR 310, for inclusion in Java
 2011 - Release of Joda-Time 2.0
 2014 - Finally, the date and time API is in
Java 8
Java 8 Date and Time API
No problems:
1. ISO 8601 order of fields - year, month, day.
2. Month 12 is December.
3. Year is 12 CE.
4. No time component.
5. No time zone.
No Problem Getting a Date
System.out.println(
LocalDate.of(12, 12, 12));
// 0012-12-12
System.out.println(
LocalDate.of(13, 13, 13));
Bad Arguments
java.time.DateTimeException: Invalid value for MonthOfYear
(valid values 1 - 12): 13
at java.time.temporal.ValueRange.checkValidValue(Unknown
Source)
at
java.time.temporal.ChronoField.checkValidValue(Unknown Source)
at java.time.LocalDate.of(Unknown Source)
…
Most importantly, the Java 8 date and time
API forces you to think carefully about what
you are doing.
Concepts
// Don’t code like this again
Calendar calendar = new GregorianCalendar();
Date date = calendar.getTime();
 Reference point to measure time
 May be based on religious or political
milestones
 Divides the timeline into eras
 Start of a particular era
Epoch
 January 0, 0 - MATLAB
 January 1, 1 - Symbian, .NET
 January 1, 1601 - COBOL, Windows
 January 1, 1900 - LISP, SNTP
 January 1, 1904 – Old Mac OS
 January 1, 1970 - Unix Epoch (Linux, Mac
OS X), Java, C, JavaScript, Perl, PHP,
Python, Ruby
Computer System Epochs
 Organizes days for social, religious,
commercial or administrative purposes
 Names periods like days, weeks, months,
and years
 Periods may follow cycles of the sun or
moon
 A date is a specific day in the system
 May be based on an epoch
Calendar System
 GMT is Greenwich Mean Time
 Mean solar time at the Royal Observatory
in Greenwich
 UTC is Coordinated Universal Time
 Precisely defined with atomic time
 Does not change with seasons
 Replaced GMT as reference time scale on
1 January 1972
UTC
 International standard for representation of
dates and times
 Uses the Gregorian calendar system
 Ordered from most to least significant:
year, month, day, hour, minute
 Each date and time value has a fixed
number of digits with leading zeros
 Uses four-digit year at minimum, YYYY
ISO 8601
http://xkcd.com/1179/
 Machines have one view of time
 discrete points corresponding to the smallest
measurement possible
 a single, ever increasing number
 Humans have a different view of time
 continuous timelines
 calendar systems
 arbitrary units like years, months, days, hours
 time zones, and daylight savings rules
Machine and Human Timelines
 Distinguish between machine and human
views
 Well-defined and clear purpose
 Immutable, thread-safe
 Reject null and bad arguments early
 Extensible, by use of strategy pattern
 Fluent interface with chained methods
Design Principles
 Point on a discretized time-line
 Stored to nanosecond resolution
 long for seconds since epoch, and
 int for nanosecond of second
 Convert to any date time field using a
Chronology
 Use for event time-stamps
Instant
 An indication of date or time that cannot
identify a specific, unique instant
 Definition uses fields such as year, month,
day of month, and time of day
 Commonly used partials, such
as LocalDate and LocalTime are available
 Others like MonthDay, YearMonth (card
expiration?) are also available
Partial
 Precise length of elapsed time, in
nanoseconds
 Does not use date-based constructs like
years, months, and days
 Can be negative, if end is before start
Duration
 A length of elapsed time
 Defined using calendar fields - years,
months, and days (not minutes and
seconds)
 Takes time zones into account for
calculation
Period
 Region with uniform standard time for
legal, commercial, social, and political
purposes
 Some countries use daylight saving time for
part of the year
 Offset from UTC (UTC-12 to UTC+14)
 UTC is sometimes denoted by Z (Zulu)
 JDK time zone data is updated with JDK
releases
Time Zone
 Gets the current instant using a time-zone
 Use instead of System.currentTimeMillis()
 Use an alternate clock for testing
Clock
public class SomeBean {
@Inject private Clock clock;
public void process() {
LocalDate date = LocalDate.now(clock);
...
}
}
 Pluggable calendar system
 Provides access to date and time fields
 Built-in
 ISO8601 (default): IsoChronology
 Chinese: MinguoChronology
 Japanese: JapaneseChronology
 Thai Buddhist: ThaiBuddhistChronology
 Islamic: HijrahChronology
Chronology
 java.time - instants, durations, dates,
times, time zones, periods
 java.time.format - formatting and parsing
 java.time.temporal - field, unit, or
adjustment access to temporals
 java.time.zone – support for time zones
 java.time.chrono - calendar systems other
than ISO-8601
New Packages
 LocalDate
 ISO 8601 date without time zone and time
 Corresponds to SQL DATE type
 Example: birthdate or employee hire-date
 LocalTime
 ISO 8601 time without time zone and date
 Corresponds to SQL TIME type
 Example: the time that an alarm clock goes off
 LocalDateTime
 ISO 8601 date and time without time zone
 Corresponds to SQL TIMESTAMP type
Commonly Used Classes
Class or Enum Year Month Day Hours Minutes Nanos
Zone
Offset
Zone
ID toString Output
Instant ✓ 2013-08-20T15:16:26.355Z
LocalDate ✓ ✓ ✓ 2013-08-20
LocalDateTime ✓ ✓ ✓ ✓ ✓ ✓ 2013-08-20T08:16:26.937
ZonedDateTime ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ 2013-08-21T00:16:26.941+09:00[Asia/Tokyo]
LocalTime ✓ ✓ ✓ 08:16:26.943
MonthDay ✓ ✓ --08-20
Year ✓ 2013
YearMonth ✓ ✓ 2013-08
Month ✓ AUGUST
OffsetDateTime ✓ ✓ ✓ ✓ ✓ ✓ ✓ 2013-08-20T08:16:26.954-07:00
OffsetTime ✓ ✓ ✓ ✓ 08:16:26.957-07:00
Duration ✓ PT20H
Period ✓ ✓ ✓ P10D
Commonly Used Classes
http://docs.oracle.com/javase/tutorial/datetime/iso/overview.html
 of - static factory, validates input
 from - static factory, converts to instance
of target class
 get - returns part of the state
 is - queries the state
 with - immutable copy with elements
changed
 to - converts to another object type
 plus, minus - immutable copy after
operation
Consistent Operations
 Day of week, for example
DayOfWeek.SUNDAY
 Month , for example
LocalDate.of(2014, Month.MAY, 20);
 Time units, for example
Instant.now().plus(1, ChronoUnit.DAYS)
 Other useful constants
 LocalTime.MIDNIGHT // 00:00
 LocalTime.NOON // 12:00
Staying Constant
 Format with a DateTimeFormatter instance
 Internationalization is supported
 Custom formats can be used, including
am/ pm for time
Formatting
 Parse with a DateTimeFormatter instance
 parse(…) methods return a temporal
 Use from(…) to convert to a known date or
time type
Parsing
TemporalAdjuster fourMinutesLater =
new TemporalAdjuster() {
@Override
public Temporal adjustInto(Temporal
temporal) {
return temporal.plus(4,
ChronoUnit.MINUTES);
}
};
LocalTime time = LocalTime.of(12, 0, 0);
LocalTime later = time.with(fourMinutesLater);
Temporal Adjusters
LocalTime time = LocalTime.of(12, 0, 0);
time.with(temporal ->
temporal.plus(4, ChronoUnit.MINUTES)));
Temporal Adjusters
Java 8 Style
 Strategy for extracting information from
temporals
 Externalize the process of querying
 Examples
 get the time zone in a temporal
 check if date is February 29 in a leap year
 calculate days until your next birthday
 TemporalQueries class has
implementations of common queries
Temporal Queries
 Existing date-related APIs can be error-
prone and tedious
 Separate concepts of computer-related
times and human-related times
Need to manipulate dates and times? Use
Joda-Time or the Java 8 date and time API.
Summary
 JSR 310: A New Java Date/Time API
 Joda-Time
 Why JSR-310 isn't Joda-Time
 Java 101: The next generation: It's time for
a change
Resources
Code used in this presentation on GitHub:
https://github.com/sualeh/java8-timeapi-examples
Code
Questions?

More Related Content

What's hot (20)

Java virtual machine
Java virtual machineJava virtual machine
Java virtual machine
baabtra.com - No. 1 supplier of quality freshers
 
Introduction to ReactJS
Introduction to ReactJSIntroduction to ReactJS
Introduction to ReactJS
Knoldus Inc.
 
Android Application Development Using Java
Android Application Development Using JavaAndroid Application Development Using Java
Android Application Development Using Java
amaankhan
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Scott Leberknight
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
Karmanjay Verma
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
jayc8586
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBoot
Josué Neis
 
Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture
AppDynamics
 
core java
core javacore java
core java
Roushan Sinha
 
Java
JavaJava
Java
sasi saseenthiran
 
Spring ppt
Spring pptSpring ppt
Spring ppt
Mumbai Academisc
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
Saba Ameer
 
Java11 New Features
Java11 New FeaturesJava11 New Features
Java11 New Features
Haim Michael
 
WebLogic Scripting Tool made Cool!
WebLogic Scripting Tool made Cool!WebLogic Scripting Tool made Cool!
WebLogic Scripting Tool made Cool!
Maarten Smeets
 
Introduction to Mobile Development
Introduction to Mobile DevelopmentIntroduction to Mobile Development
Introduction to Mobile Development
Pragnesh Vaghela
 
Introduction to Java -unit-1
Introduction to Java -unit-1Introduction to Java -unit-1
Introduction to Java -unit-1
RubaNagarajan
 
Declarative UIs with Jetpack Compose
Declarative UIs with Jetpack ComposeDeclarative UIs with Jetpack Compose
Declarative UIs with Jetpack Compose
Ramon Ribeiro Rabello
 
Android Development: The Basics
Android Development: The BasicsAndroid Development: The Basics
Android Development: The Basics
Mike Desjardins
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
NAVER Engineering
 
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
Java Programming | Java Tutorial For Beginners | Java Training | EdurekaJava Programming | Java Tutorial For Beginners | Java Training | Edureka
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
Edureka!
 
Introduction to ReactJS
Introduction to ReactJSIntroduction to ReactJS
Introduction to ReactJS
Knoldus Inc.
 
Android Application Development Using Java
Android Application Development Using JavaAndroid Application Development Using Java
Android Application Development Using Java
amaankhan
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
Karmanjay Verma
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
jayc8586
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBoot
Josué Neis
 
Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture
AppDynamics
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
Saba Ameer
 
Java11 New Features
Java11 New FeaturesJava11 New Features
Java11 New Features
Haim Michael
 
WebLogic Scripting Tool made Cool!
WebLogic Scripting Tool made Cool!WebLogic Scripting Tool made Cool!
WebLogic Scripting Tool made Cool!
Maarten Smeets
 
Introduction to Mobile Development
Introduction to Mobile DevelopmentIntroduction to Mobile Development
Introduction to Mobile Development
Pragnesh Vaghela
 
Introduction to Java -unit-1
Introduction to Java -unit-1Introduction to Java -unit-1
Introduction to Java -unit-1
RubaNagarajan
 
Declarative UIs with Jetpack Compose
Declarative UIs with Jetpack ComposeDeclarative UIs with Jetpack Compose
Declarative UIs with Jetpack Compose
Ramon Ribeiro Rabello
 
Android Development: The Basics
Android Development: The BasicsAndroid Development: The Basics
Android Development: The Basics
Mike Desjardins
 
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
Java Programming | Java Tutorial For Beginners | Java Training | EdurekaJava Programming | Java Tutorial For Beginners | Java Training | Edureka
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
Edureka!
 

Viewers also liked (20)

Sailing with Java 8 Streams
Sailing with Java 8 StreamsSailing with Java 8 Streams
Sailing with Java 8 Streams
Ganesh Samarthyam
 
Short history of time - Confitura 2013
Short history of time - Confitura 2013Short history of time - Confitura 2013
Short history of time - Confitura 2013
nurkiewicz
 
Groovy Tutorial
Groovy TutorialGroovy Tutorial
Groovy Tutorial
Paul King
 
Java 8 date & time
Java 8 date & timeJava 8 date & time
Java 8 date & time
Oleg Tsal-Tsalko
 
Spring MVC - QConSP
Spring MVC - QConSPSpring MVC - QConSP
Spring MVC - QConSP
Eduardo Bregaida
 
Cultura da empresa - um problema na adoção ágil
Cultura da empresa - um problema na adoção ágilCultura da empresa - um problema na adoção ágil
Cultura da empresa - um problema na adoção ágil
Eduardo Bregaida
 
Java Generics - Quiz Questions
Java Generics - Quiz QuestionsJava Generics - Quiz Questions
Java Generics - Quiz Questions
Ganesh Samarthyam
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz Questions
Ganesh Samarthyam
 
Chap01
Chap01Chap01
Chap01
Terry Yoast
 
9781111530532 ppt ch14
9781111530532 ppt ch149781111530532 ppt ch14
9781111530532 ppt ch14
Terry Yoast
 
9781285852744 ppt ch16
9781285852744 ppt ch169781285852744 ppt ch16
9781285852744 ppt ch16
Terry Yoast
 
DDD + BDD + TDD + Scrum
DDD + BDD + TDD + ScrumDDD + BDD + TDD + Scrum
DDD + BDD + TDD + Scrum
Eduardo Bregaida
 
AWS Innovate: AWS Container Management using Amazon EC2 Container Service an...
AWS Innovate:  AWS Container Management using Amazon EC2 Container Service an...AWS Innovate:  AWS Container Management using Amazon EC2 Container Service an...
AWS Innovate: AWS Container Management using Amazon EC2 Container Service an...
Amazon Web Services Korea
 
Data Structures- Part9 trees simplified
Data Structures- Part9 trees simplifiedData Structures- Part9 trees simplified
Data Structures- Part9 trees simplified
Abdullah Al-hazmy
 
Data Structures- Part8 stacks and queues
Data Structures- Part8 stacks and queuesData Structures- Part8 stacks and queues
Data Structures- Part8 stacks and queues
Abdullah Al-hazmy
 
Data Structures- Part2 analysis tools
Data Structures- Part2 analysis toolsData Structures- Part2 analysis tools
Data Structures- Part2 analysis tools
Abdullah Al-hazmy
 
OCJP Samples Questions: Exceptions and assertions
OCJP Samples Questions: Exceptions and assertionsOCJP Samples Questions: Exceptions and assertions
OCJP Samples Questions: Exceptions and assertions
Hari kiran G
 
DDD - Linguagem Ubíqua
DDD - Linguagem UbíquaDDD - Linguagem Ubíqua
DDD - Linguagem Ubíqua
Eduardo Bregaida
 
Applying Design Patterns in Practice
Applying Design Patterns in PracticeApplying Design Patterns in Practice
Applying Design Patterns in Practice
Ganesh Samarthyam
 
Get into Functional Programming with Clojure
Get into Functional Programming with ClojureGet into Functional Programming with Clojure
Get into Functional Programming with Clojure
John Stevenson
 
Short history of time - Confitura 2013
Short history of time - Confitura 2013Short history of time - Confitura 2013
Short history of time - Confitura 2013
nurkiewicz
 
Groovy Tutorial
Groovy TutorialGroovy Tutorial
Groovy Tutorial
Paul King
 
Cultura da empresa - um problema na adoção ágil
Cultura da empresa - um problema na adoção ágilCultura da empresa - um problema na adoção ágil
Cultura da empresa - um problema na adoção ágil
Eduardo Bregaida
 
Java Generics - Quiz Questions
Java Generics - Quiz QuestionsJava Generics - Quiz Questions
Java Generics - Quiz Questions
Ganesh Samarthyam
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz Questions
Ganesh Samarthyam
 
9781111530532 ppt ch14
9781111530532 ppt ch149781111530532 ppt ch14
9781111530532 ppt ch14
Terry Yoast
 
9781285852744 ppt ch16
9781285852744 ppt ch169781285852744 ppt ch16
9781285852744 ppt ch16
Terry Yoast
 
AWS Innovate: AWS Container Management using Amazon EC2 Container Service an...
AWS Innovate:  AWS Container Management using Amazon EC2 Container Service an...AWS Innovate:  AWS Container Management using Amazon EC2 Container Service an...
AWS Innovate: AWS Container Management using Amazon EC2 Container Service an...
Amazon Web Services Korea
 
Data Structures- Part9 trees simplified
Data Structures- Part9 trees simplifiedData Structures- Part9 trees simplified
Data Structures- Part9 trees simplified
Abdullah Al-hazmy
 
Data Structures- Part8 stacks and queues
Data Structures- Part8 stacks and queuesData Structures- Part8 stacks and queues
Data Structures- Part8 stacks and queues
Abdullah Al-hazmy
 
Data Structures- Part2 analysis tools
Data Structures- Part2 analysis toolsData Structures- Part2 analysis tools
Data Structures- Part2 analysis tools
Abdullah Al-hazmy
 
OCJP Samples Questions: Exceptions and assertions
OCJP Samples Questions: Exceptions and assertionsOCJP Samples Questions: Exceptions and assertions
OCJP Samples Questions: Exceptions and assertions
Hari kiran G
 
Applying Design Patterns in Practice
Applying Design Patterns in PracticeApplying Design Patterns in Practice
Applying Design Patterns in Practice
Ganesh Samarthyam
 
Get into Functional Programming with Clojure
Get into Functional Programming with ClojureGet into Functional Programming with Clojure
Get into Functional Programming with Clojure
John Stevenson
 
Ad

Similar to Java 8 Date and Time API (20)

Dates and Times in Java 7 and Java 8
Dates and Times in Java 7 and Java 8Dates and Times in Java 7 and Java 8
Dates and Times in Java 7 and Java 8
Fulvio Corno
 
Date and Time Odds Ends Oddities
Date and Time Odds Ends OdditiesDate and Time Odds Ends Oddities
Date and Time Odds Ends Oddities
Maggie Pint
 
17 ruby date time
17 ruby date time17 ruby date time
17 ruby date time
Walker Maidana
 
Data Wrangling: Working with Date / Time Data and Visualizing It
Data Wrangling: Working with Date / Time Data and Visualizing ItData Wrangling: Working with Date / Time Data and Visualizing It
Data Wrangling: Working with Date / Time Data and Visualizing It
kanaugust
 
Introduction to Date and Time API 4
Introduction to Date and Time API 4Introduction to Date and Time API 4
Introduction to Date and Time API 4
Kenji HASUNUMA
 
Introduction to Date and Time API 4
Introduction to Date and Time API 4Introduction to Date and Time API 4
Introduction to Date and Time API 4
Kenji HASUNUMA
 
doc
docdoc
doc
PlanetExpressATX
 
jkfdlsajfklafj
jkfdlsajfklafjjkfdlsajfklafj
jkfdlsajfklafj
PlanetExpressATX
 
Fun times with ruby
Fun times with rubyFun times with ruby
Fun times with ruby
Geoff Harcourt
 
JSR 310. New Date API in Java 8
JSR 310. New Date API in Java 8JSR 310. New Date API in Java 8
JSR 310. New Date API in Java 8
Serhii Kartashov
 
How to work with dates and times in swift 3
How to work with dates and times in swift 3How to work with dates and times in swift 3
How to work with dates and times in swift 3
allanh0526
 
Php date & time functions
Php date & time functionsPhp date & time functions
Php date & time functions
Programmer Blog
 
27- System Funciton in Azure Data Factory.pptx
27- System Funciton in Azure Data Factory.pptx27- System Funciton in Azure Data Factory.pptx
27- System Funciton in Azure Data Factory.pptx
BRIJESH KUMAR
 
Date and time manipulation
Date and time manipulationDate and time manipulation
Date and time manipulation
Shahjahan Samoon
 
Date and Timestamp Types In Snowflake (By Faysal Shaarani)
Date and Timestamp Types In Snowflake (By Faysal Shaarani)Date and Timestamp Types In Snowflake (By Faysal Shaarani)
Date and Timestamp Types In Snowflake (By Faysal Shaarani)
Faysal Shaarani (MBA)
 
Brand new Date and Time API
Brand new Date and Time APIBrand new Date and Time API
Brand new Date and Time API
Kenji HASUNUMA
 
Brand New Date and Time API
Brand New Date and Time APIBrand New Date and Time API
Brand New Date and Time API
Kenji HASUNUMA
 
Date and Time MomentJS Edition
Date and Time MomentJS EditionDate and Time MomentJS Edition
Date and Time MomentJS Edition
Maggie Pint
 
Demystifying Temporal
Demystifying                    TemporalDemystifying                    Temporal
Demystifying Temporal
Igalia
 
Lesson 05 - Time in Distrributed System.pptx
Lesson 05 - Time in Distrributed System.pptxLesson 05 - Time in Distrributed System.pptx
Lesson 05 - Time in Distrributed System.pptx
LagamaPasala
 
Dates and Times in Java 7 and Java 8
Dates and Times in Java 7 and Java 8Dates and Times in Java 7 and Java 8
Dates and Times in Java 7 and Java 8
Fulvio Corno
 
Date and Time Odds Ends Oddities
Date and Time Odds Ends OdditiesDate and Time Odds Ends Oddities
Date and Time Odds Ends Oddities
Maggie Pint
 
Data Wrangling: Working with Date / Time Data and Visualizing It
Data Wrangling: Working with Date / Time Data and Visualizing ItData Wrangling: Working with Date / Time Data and Visualizing It
Data Wrangling: Working with Date / Time Data and Visualizing It
kanaugust
 
Introduction to Date and Time API 4
Introduction to Date and Time API 4Introduction to Date and Time API 4
Introduction to Date and Time API 4
Kenji HASUNUMA
 
Introduction to Date and Time API 4
Introduction to Date and Time API 4Introduction to Date and Time API 4
Introduction to Date and Time API 4
Kenji HASUNUMA
 
JSR 310. New Date API in Java 8
JSR 310. New Date API in Java 8JSR 310. New Date API in Java 8
JSR 310. New Date API in Java 8
Serhii Kartashov
 
How to work with dates and times in swift 3
How to work with dates and times in swift 3How to work with dates and times in swift 3
How to work with dates and times in swift 3
allanh0526
 
Php date & time functions
Php date & time functionsPhp date & time functions
Php date & time functions
Programmer Blog
 
27- System Funciton in Azure Data Factory.pptx
27- System Funciton in Azure Data Factory.pptx27- System Funciton in Azure Data Factory.pptx
27- System Funciton in Azure Data Factory.pptx
BRIJESH KUMAR
 
Date and time manipulation
Date and time manipulationDate and time manipulation
Date and time manipulation
Shahjahan Samoon
 
Date and Timestamp Types In Snowflake (By Faysal Shaarani)
Date and Timestamp Types In Snowflake (By Faysal Shaarani)Date and Timestamp Types In Snowflake (By Faysal Shaarani)
Date and Timestamp Types In Snowflake (By Faysal Shaarani)
Faysal Shaarani (MBA)
 
Brand new Date and Time API
Brand new Date and Time APIBrand new Date and Time API
Brand new Date and Time API
Kenji HASUNUMA
 
Brand New Date and Time API
Brand New Date and Time APIBrand New Date and Time API
Brand New Date and Time API
Kenji HASUNUMA
 
Date and Time MomentJS Edition
Date and Time MomentJS EditionDate and Time MomentJS Edition
Date and Time MomentJS Edition
Maggie Pint
 
Demystifying Temporal
Demystifying                    TemporalDemystifying                    Temporal
Demystifying Temporal
Igalia
 
Lesson 05 - Time in Distrributed System.pptx
Lesson 05 - Time in Distrributed System.pptxLesson 05 - Time in Distrributed System.pptx
Lesson 05 - Time in Distrributed System.pptx
LagamaPasala
 
Ad

More from Sualeh Fatehi (16)

Magic Wheels (1987)
Magic Wheels (1987)Magic Wheels (1987)
Magic Wheels (1987)
Sualeh Fatehi
 
The Geometry of Stars
The Geometry of StarsThe Geometry of Stars
The Geometry of Stars
Sualeh Fatehi
 
Blue Moon
Blue MoonBlue Moon
Blue Moon
Sualeh Fatehi
 
Magic Wheels
Magic WheelsMagic Wheels
Magic Wheels
Sualeh Fatehi
 
Conversion of Roman Numbers to Hindu-Arabic
Conversion of Roman Numbers to Hindu-ArabicConversion of Roman Numbers to Hindu-Arabic
Conversion of Roman Numbers to Hindu-Arabic
Sualeh Fatehi
 
X.400
X.400X.400
X.400
Sualeh Fatehi
 
GFN News
GFN NewsGFN News
GFN News
Sualeh Fatehi
 
Swedish Rite
Swedish RiteSwedish Rite
Swedish Rite
Sualeh Fatehi
 
Freemasonry in India
Freemasonry in IndiaFreemasonry in India
Freemasonry in India
Sualeh Fatehi
 
SchemaCrawler
SchemaCrawlerSchemaCrawler
SchemaCrawler
Sualeh Fatehi
 
Cubic Insanity
Cubic InsanityCubic Insanity
Cubic Insanity
Sualeh Fatehi
 
Beyond the Mobius Strip
Beyond the Mobius StripBeyond the Mobius Strip
Beyond the Mobius Strip
Sualeh Fatehi
 
Tofiks Dodecahedron
Tofiks DodecahedronTofiks Dodecahedron
Tofiks Dodecahedron
Sualeh Fatehi
 
Pythagorean Triplets
Pythagorean TripletsPythagorean Triplets
Pythagorean Triplets
Sualeh Fatehi
 
Dissection Of The Dodecahedron
Dissection Of The DodecahedronDissection Of The Dodecahedron
Dissection Of The Dodecahedron
Sualeh Fatehi
 
The Eleven Holes Puzzle
The Eleven Holes PuzzleThe Eleven Holes Puzzle
The Eleven Holes Puzzle
Sualeh Fatehi
 

Recently uploaded (20)

STKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 versionSTKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 version
Dr. Jimmy Schwarzkopf
 
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Nikki Chapple
 
UiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPath Community Berlin: Studio Tips & Tricks and UiPath InsightsUiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPathCommunity
 
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 ADr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr. Jimmy Schwarzkopf
 
Offshore IT Support: Balancing In-House and Offshore Help Desk Technicians
Offshore IT Support: Balancing In-House and Offshore Help Desk TechniciansOffshore IT Support: Balancing In-House and Offshore Help Desk Technicians
Offshore IT Support: Balancing In-House and Offshore Help Desk Technicians
john823664
 
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptxECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
Jasper Oosterveld
 
Fortinet Certified Associate in Cybersecurity
Fortinet Certified Associate in CybersecurityFortinet Certified Associate in Cybersecurity
Fortinet Certified Associate in Cybersecurity
VICTOR MAESTRE RAMIREZ
 
SDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhereSDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhere
Adtran
 
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyesEnd-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
ThousandEyes
 
Cognitive Chasms - A Typology of GenAI Failure Failure Modes
Cognitive Chasms - A Typology of GenAI Failure Failure ModesCognitive Chasms - A Typology of GenAI Failure Failure Modes
Cognitive Chasms - A Typology of GenAI Failure Failure Modes
Dr. Tathagat Varma
 
Supercharge Your AI Development with Local LLMs
Supercharge Your AI Development with Local LLMsSupercharge Your AI Development with Local LLMs
Supercharge Your AI Development with Local LLMs
Francesco Corti
 
AI Trends - Mary Meeker
AI Trends - Mary MeekerAI Trends - Mary Meeker
AI Trends - Mary Meeker
Razin Mustafiz
 
Cyber Security Legal Framework in Nepal.pptx
Cyber Security Legal Framework in Nepal.pptxCyber Security Legal Framework in Nepal.pptx
Cyber Security Legal Framework in Nepal.pptx
Ghimire B.R.
 
Dev Dives: System-to-system integration with UiPath API Workflows
Dev Dives: System-to-system integration with UiPath API WorkflowsDev Dives: System-to-system integration with UiPath API Workflows
Dev Dives: System-to-system integration with UiPath API Workflows
UiPathCommunity
 
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Lorenzo Miniero
 
Droidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing HealthcareDroidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing Healthcare
Droidal LLC
 
Palo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity FoundationPalo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity Foundation
VICTOR MAESTRE RAMIREZ
 
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AI Emotional Actors:  “When Machines Learn to Feel and Perform"AI Emotional Actors:  “When Machines Learn to Feel and Perform"
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AkashKumar809858
 
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
Jasper Oosterveld
 
Measuring Microsoft 365 Copilot and Gen AI Success
Measuring Microsoft 365 Copilot and Gen AI SuccessMeasuring Microsoft 365 Copilot and Gen AI Success
Measuring Microsoft 365 Copilot and Gen AI Success
Nikki Chapple
 
STKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 versionSTKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 version
Dr. Jimmy Schwarzkopf
 
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Nikki Chapple
 
UiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPath Community Berlin: Studio Tips & Tricks and UiPath InsightsUiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPathCommunity
 
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 ADr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr. Jimmy Schwarzkopf
 
Offshore IT Support: Balancing In-House and Offshore Help Desk Technicians
Offshore IT Support: Balancing In-House and Offshore Help Desk TechniciansOffshore IT Support: Balancing In-House and Offshore Help Desk Technicians
Offshore IT Support: Balancing In-House and Offshore Help Desk Technicians
john823664
 
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptxECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
Jasper Oosterveld
 
Fortinet Certified Associate in Cybersecurity
Fortinet Certified Associate in CybersecurityFortinet Certified Associate in Cybersecurity
Fortinet Certified Associate in Cybersecurity
VICTOR MAESTRE RAMIREZ
 
SDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhereSDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhere
Adtran
 
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyesEnd-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
ThousandEyes
 
Cognitive Chasms - A Typology of GenAI Failure Failure Modes
Cognitive Chasms - A Typology of GenAI Failure Failure ModesCognitive Chasms - A Typology of GenAI Failure Failure Modes
Cognitive Chasms - A Typology of GenAI Failure Failure Modes
Dr. Tathagat Varma
 
Supercharge Your AI Development with Local LLMs
Supercharge Your AI Development with Local LLMsSupercharge Your AI Development with Local LLMs
Supercharge Your AI Development with Local LLMs
Francesco Corti
 
AI Trends - Mary Meeker
AI Trends - Mary MeekerAI Trends - Mary Meeker
AI Trends - Mary Meeker
Razin Mustafiz
 
Cyber Security Legal Framework in Nepal.pptx
Cyber Security Legal Framework in Nepal.pptxCyber Security Legal Framework in Nepal.pptx
Cyber Security Legal Framework in Nepal.pptx
Ghimire B.R.
 
Dev Dives: System-to-system integration with UiPath API Workflows
Dev Dives: System-to-system integration with UiPath API WorkflowsDev Dives: System-to-system integration with UiPath API Workflows
Dev Dives: System-to-system integration with UiPath API Workflows
UiPathCommunity
 
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Lorenzo Miniero
 
Droidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing HealthcareDroidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing Healthcare
Droidal LLC
 
Palo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity FoundationPalo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity Foundation
VICTOR MAESTRE RAMIREZ
 
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AI Emotional Actors:  “When Machines Learn to Feel and Perform"AI Emotional Actors:  “When Machines Learn to Feel and Perform"
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AkashKumar809858
 
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
Jasper Oosterveld
 
Measuring Microsoft 365 Copilot and Gen AI Success
Measuring Microsoft 365 Copilot and Gen AI SuccessMeasuring Microsoft 365 Copilot and Gen AI Success
Measuring Microsoft 365 Copilot and Gen AI Success
Nikki Chapple
 

Java 8 Date and Time API

  • 1. Sualeh Fatehi Java 8 Date and Time API This work by Sualeh Fatehi is licensed under a Creative Commons Attribution- NonCommercial 4.0 International License.
  • 2.  Review the current date and time API  Understand date and time concepts  Take a look at the new date and time API Overview
  • 3. Several problems here: 1. Which 12 is for which date field? 2. Month 12 is December, right? No. January. 3. Year 12 is 12 CE, right? Wrong. 1913. 4. Wait - there is a time in a date? 5. More than that, there is a time zone. Problems Getting a Date System.out.println(new Date(12, 12, 12)); // Sun Jan 12 00:00:00 EST 1913
  • 4.  Conceptually an instant, not a date  Properties have random offsets  Some zero-based, like month and hours  Some one-based, like day of the month  Year has an offset of 1900  Mutable, not thread-safe  Not internationalizable  Millisecond granularity  Does not reflect UTC A Sorry Implementation
  • 5.  Date was the work of James Gosling and Arthur van Hoff  Added in JDK 1.0, mostly deprecated in JDK 1.1, never removed  IBM donated Calendar code to Sun Back Story
  • 6. System.out.println(new GregorianCalendar(12, 12, 12)); Revisited Examples java.util.GregorianCalendar[time=?,areFieldsSet=false,areA llFieldsSet=false,lenient=true,zone=sun.util.calendar.Zone Info[id="America/New_York",offset=- 18000000,dstSavings=3600000,useDaylight=true,transitions=2 35,lastRule=java.util.Simpletime zone[id=America/New_York,offset=- 18000000,dstSavings=3600000,useDaylight=true,startYear=0,s tartMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startT ime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1 ,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOf Week=1,minimalDaysInFirstWeek=1,ERA=?,YEAR=12,MONTH=12,WEE K_OF_YEAR=?,WEEK_OF_MONTH=?,DAY_OF_MONTH=12,DAY_OF_YEAR=?, DAY_OF_WEEK=?,DAY_OF_WEEK_IN_MONTH=?,AM_PM=0,HOUR=0,HOUR_O F_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=?,ZONE_OFFSET=?,DST_ OFFSET=?]
  • 7. Several problems here: 1. Which 12 is for which date field? 2. Month 12 is December, right? No. January. 3. They got the year right! Almost. 13 CE. 4. Wait - there is a time in a calendar? 5. More than that, there is a time zone. Problems Getting a Date System.out.println(dtFmt.format(new GregorianCalendar(12,12,12).getTime())); // January 12, 0013 12:00:00 AM EST
  • 8.  “Calendar” represents a date, time and time-zone  Defaults to Gregorian calendar  In Thailand only, you get a Buddhist calendar  You can ask specifically ask for a Japanese calendar Calendar
  • 9.  Conceptually an instant, not a calendar  But, can’t create a Calendar from a Date  Can’t format a Calendar  Zero-based offsets  Stores internal state in two different ways  milliseconds from epoch  set of fields  Has bugs and performance issues  Mutable, not thread-safe Not Much Improvement
  • 10.  2002 - Stephen Colebourne starts open source Joda-Time project  2005 - Release of Joda-Time 1.0  2007 - JSR 310, for inclusion in Java  2011 - Release of Joda-Time 2.0  2014 - Finally, the date and time API is in Java 8 Java 8 Date and Time API
  • 11. No problems: 1. ISO 8601 order of fields - year, month, day. 2. Month 12 is December. 3. Year is 12 CE. 4. No time component. 5. No time zone. No Problem Getting a Date System.out.println( LocalDate.of(12, 12, 12)); // 0012-12-12
  • 12. System.out.println( LocalDate.of(13, 13, 13)); Bad Arguments java.time.DateTimeException: Invalid value for MonthOfYear (valid values 1 - 12): 13 at java.time.temporal.ValueRange.checkValidValue(Unknown Source) at java.time.temporal.ChronoField.checkValidValue(Unknown Source) at java.time.LocalDate.of(Unknown Source) …
  • 13. Most importantly, the Java 8 date and time API forces you to think carefully about what you are doing. Concepts // Don’t code like this again Calendar calendar = new GregorianCalendar(); Date date = calendar.getTime();
  • 14.  Reference point to measure time  May be based on religious or political milestones  Divides the timeline into eras  Start of a particular era Epoch
  • 15.  January 0, 0 - MATLAB  January 1, 1 - Symbian, .NET  January 1, 1601 - COBOL, Windows  January 1, 1900 - LISP, SNTP  January 1, 1904 – Old Mac OS  January 1, 1970 - Unix Epoch (Linux, Mac OS X), Java, C, JavaScript, Perl, PHP, Python, Ruby Computer System Epochs
  • 16.  Organizes days for social, religious, commercial or administrative purposes  Names periods like days, weeks, months, and years  Periods may follow cycles of the sun or moon  A date is a specific day in the system  May be based on an epoch Calendar System
  • 17.  GMT is Greenwich Mean Time  Mean solar time at the Royal Observatory in Greenwich  UTC is Coordinated Universal Time  Precisely defined with atomic time  Does not change with seasons  Replaced GMT as reference time scale on 1 January 1972 UTC
  • 18.  International standard for representation of dates and times  Uses the Gregorian calendar system  Ordered from most to least significant: year, month, day, hour, minute  Each date and time value has a fixed number of digits with leading zeros  Uses four-digit year at minimum, YYYY ISO 8601
  • 20.  Machines have one view of time  discrete points corresponding to the smallest measurement possible  a single, ever increasing number  Humans have a different view of time  continuous timelines  calendar systems  arbitrary units like years, months, days, hours  time zones, and daylight savings rules Machine and Human Timelines
  • 21.  Distinguish between machine and human views  Well-defined and clear purpose  Immutable, thread-safe  Reject null and bad arguments early  Extensible, by use of strategy pattern  Fluent interface with chained methods Design Principles
  • 22.  Point on a discretized time-line  Stored to nanosecond resolution  long for seconds since epoch, and  int for nanosecond of second  Convert to any date time field using a Chronology  Use for event time-stamps Instant
  • 23.  An indication of date or time that cannot identify a specific, unique instant  Definition uses fields such as year, month, day of month, and time of day  Commonly used partials, such as LocalDate and LocalTime are available  Others like MonthDay, YearMonth (card expiration?) are also available Partial
  • 24.  Precise length of elapsed time, in nanoseconds  Does not use date-based constructs like years, months, and days  Can be negative, if end is before start Duration
  • 25.  A length of elapsed time  Defined using calendar fields - years, months, and days (not minutes and seconds)  Takes time zones into account for calculation Period
  • 26.  Region with uniform standard time for legal, commercial, social, and political purposes  Some countries use daylight saving time for part of the year  Offset from UTC (UTC-12 to UTC+14)  UTC is sometimes denoted by Z (Zulu)  JDK time zone data is updated with JDK releases Time Zone
  • 27.  Gets the current instant using a time-zone  Use instead of System.currentTimeMillis()  Use an alternate clock for testing Clock public class SomeBean { @Inject private Clock clock; public void process() { LocalDate date = LocalDate.now(clock); ... } }
  • 28.  Pluggable calendar system  Provides access to date and time fields  Built-in  ISO8601 (default): IsoChronology  Chinese: MinguoChronology  Japanese: JapaneseChronology  Thai Buddhist: ThaiBuddhistChronology  Islamic: HijrahChronology Chronology
  • 29.  java.time - instants, durations, dates, times, time zones, periods  java.time.format - formatting and parsing  java.time.temporal - field, unit, or adjustment access to temporals  java.time.zone – support for time zones  java.time.chrono - calendar systems other than ISO-8601 New Packages
  • 30.  LocalDate  ISO 8601 date without time zone and time  Corresponds to SQL DATE type  Example: birthdate or employee hire-date  LocalTime  ISO 8601 time without time zone and date  Corresponds to SQL TIME type  Example: the time that an alarm clock goes off  LocalDateTime  ISO 8601 date and time without time zone  Corresponds to SQL TIMESTAMP type Commonly Used Classes
  • 31. Class or Enum Year Month Day Hours Minutes Nanos Zone Offset Zone ID toString Output Instant ✓ 2013-08-20T15:16:26.355Z LocalDate ✓ ✓ ✓ 2013-08-20 LocalDateTime ✓ ✓ ✓ ✓ ✓ ✓ 2013-08-20T08:16:26.937 ZonedDateTime ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ 2013-08-21T00:16:26.941+09:00[Asia/Tokyo] LocalTime ✓ ✓ ✓ 08:16:26.943 MonthDay ✓ ✓ --08-20 Year ✓ 2013 YearMonth ✓ ✓ 2013-08 Month ✓ AUGUST OffsetDateTime ✓ ✓ ✓ ✓ ✓ ✓ ✓ 2013-08-20T08:16:26.954-07:00 OffsetTime ✓ ✓ ✓ ✓ 08:16:26.957-07:00 Duration ✓ PT20H Period ✓ ✓ ✓ P10D Commonly Used Classes http://docs.oracle.com/javase/tutorial/datetime/iso/overview.html
  • 32.  of - static factory, validates input  from - static factory, converts to instance of target class  get - returns part of the state  is - queries the state  with - immutable copy with elements changed  to - converts to another object type  plus, minus - immutable copy after operation Consistent Operations
  • 33.  Day of week, for example DayOfWeek.SUNDAY  Month , for example LocalDate.of(2014, Month.MAY, 20);  Time units, for example Instant.now().plus(1, ChronoUnit.DAYS)  Other useful constants  LocalTime.MIDNIGHT // 00:00  LocalTime.NOON // 12:00 Staying Constant
  • 34.  Format with a DateTimeFormatter instance  Internationalization is supported  Custom formats can be used, including am/ pm for time Formatting
  • 35.  Parse with a DateTimeFormatter instance  parse(…) methods return a temporal  Use from(…) to convert to a known date or time type Parsing
  • 36. TemporalAdjuster fourMinutesLater = new TemporalAdjuster() { @Override public Temporal adjustInto(Temporal temporal) { return temporal.plus(4, ChronoUnit.MINUTES); } }; LocalTime time = LocalTime.of(12, 0, 0); LocalTime later = time.with(fourMinutesLater); Temporal Adjusters
  • 37. LocalTime time = LocalTime.of(12, 0, 0); time.with(temporal -> temporal.plus(4, ChronoUnit.MINUTES))); Temporal Adjusters Java 8 Style
  • 38.  Strategy for extracting information from temporals  Externalize the process of querying  Examples  get the time zone in a temporal  check if date is February 29 in a leap year  calculate days until your next birthday  TemporalQueries class has implementations of common queries Temporal Queries
  • 39.  Existing date-related APIs can be error- prone and tedious  Separate concepts of computer-related times and human-related times Need to manipulate dates and times? Use Joda-Time or the Java 8 date and time API. Summary
  • 40.  JSR 310: A New Java Date/Time API  Joda-Time  Why JSR-310 isn't Joda-Time  Java 101: The next generation: It's time for a change Resources
  • 41. Code used in this presentation on GitHub: https://github.com/sualeh/java8-timeapi-examples Code