SlideShare ist ein Scribd-Unternehmen logo
1 von 23
New Date & Time API of Java8 
- Buddha Jyothiprasad
Agenda 
 A Quick look at Old API 
for Date and Time 
 Discuss the issues with 
it 
 Introduce the new API 
from Java 8 
 See some examples of 
various concepts in new 
API 
Buddha Java User Group - Hyderabad
A Quick Look at old API 
 java.util.Date 
 java.sql.Date 
 Calendar 
 GregorianCalendar 
 TimeZone 
 DateFormat 
 SimpleDateFormat 
Some bugs that doesn’t look like Bugs with old 
API 
3 Java User Group - Hyderabad
Issues with the old approach 
Ø Date is actually DateTime 
Ø Different class for SQL 
Ø Date doesn’t have timezone 
Ø getMonth() is zero-based, getYear() is 1900-based 
(i.e., the year 2009 is represented as 109) 
Ø Mutable hence not thread-safe by default 
Ø java.util.Date represents an instant on the timeline 
but invoking toString() prints time stamp along with 
time zone, causing confusion among developers 
Ø Calendar can’t format date directly 
Ø Arithmetic operations are still tricky 
Buddha Java User Group - Hyderabad
Fixed Code that doesn’t look right 
Buddha Java User Group - Hyderabad
New API 
 New package java.time 
 New classes LocalDate, 
LocalTime 
 A composite class 
LocalDateTime 
 Supports numerous 
ways of creating Date 
and Time objects 
 Supports Truncation, 
Timezones, Periods, 
Durations, Chronologies 
ANSI SQL Java SE 8 
DATE LocalDate 
TIME LocalTime 
TIMESTAMP LocalDateTime 
TIME WITH TIMEZONE OffsetTime 
TIMESTAMP WITH 
TIMEZONE 
OffsetDateTime 
And many more…. 
6 Java User Group - Hyderabad
Java 8 packages for Date & Time 
• Consists of major base classes 
• LocalDate, LocalTime, Instant, Duration 
java.time 
• Consists of generic API for non ISO Calendar 
Systems java.time.chrono 
• Contains temporal objects to find out specific 
date/time related like firstDay of month java.time.temporal 
• Classes for formatting and parsing date time 
objects java.time.format 
java.time.zone • Classes for supporting different timezones 
Buddha Java User Group - Hyderabad
Creating Objects 
 All the core classes are 
constructed by fluent 
factory methods 
 When constructing a 
value by its constituent 
fields, the factory is 
called of 
 when converting from 
another type, the factory 
is called from 
 There are also parse 
methods that take strings 
as parameters 
 Standard Java getter 
conventions are used in 
order to obtain values 
8 Java User Group - Hyderabad
Code for Creating Date & Time Objects 
9 Java User Group - Hyderabad
Date & Time manipulation 
 We can alter the object 
values in order to perform 
calculations 
 All objects are immutable 
 Setters are no more 
 New API also has a 
concept of Adjuster 
methods 
 These methods are called 
with and return new 
objects 
 There are also plus 
adjusters 
 We can write our own with 
adjusters and plus 
adjusters 
10 Java User Group - Hyderabad
Date Manipulation examples 
11 Java User Group - Hyderabad
Time Zones 
 The local classes that we 
looked at previously 
abstract away the 
complexity introduced by 
time zones 
 ZonedDateTime is a date 
and time with a fully 
qualified time zone 
 This can resolve an offset 
at any point in time 
 Other classes are ZoneId, 
ZoneOffset, 
OffsetDateTime, 
12OffsetTime Java User Group - Hyderabad
Time Zone examples 
13 Java User Group - Hyderabad
Instant, Periods & Duration 
 Instant is the closest sibling of java.util.Date. Instant 
class is used to work with machine readable time 
format, it stores date time in unix timestamp. 
 A Period represents a value such as “3 months and 
1 day,” 
 A Duration is a distance on the timeline measured in 
terms of time, and it fulfills a similar purpose 
to Period, but with different precision 
Buddha Java User Group - Hyderabad
Code snippets 
Buddha Java User Group - Hyderabad
Parsing & Formatting 
 Every class in date time 
formatter has methods for 
parsing and formatting 
 format() and parse() 
directly on the date 
objects 
 DateTimeFormatter 
 Loads of Predefined 
formatters like ISO_DATE 
 Custom formats can also 
be provided via 
DateTimeFormatter.ofPa 
ttern() method 
16 Java User Group - Hyderabad
Parsing & Formatting snippets 
17 Java User Group - Hyderabad
Query 
 A TemporalQuery can be used to retrieve 
information from a temporal-based object 
 The TemporalQueries class(note the plural) 
provides several predefined queries 
 The precision query, for example, returns the 
smallest ChronoUnit that can be returned by a 
particular temporal-based object 
 We can also create custom queries by implementing 
the interface TemporaryQuery 
18 Java User Group - Hyderabad
Working with Custom Queries 
Buddha Java User Group - Hyderabad
Legacy Support 
 Legacy Date/Time 
classes are used in 
almost all the 
applications 
 Backward compatibility 
is a must 
 Following Utility 
methods are provided 
for that purpose 
 toInstant() 
 toZoneId() 
 from() 
20 Java User Group - Hyderabad
Summary 
 Immutability: All the classes in the new API are immutable hence 
they are thread-safe. 
 Separation of Concerns: The new API separates clearly between 
human readable date time and machine time. It defines separate 
classes for Date, Time, DateTime, Timestamp etc. 
 Consistency: The methods are clearly defined and perform the 
same action in all the classes. There are format() and parse() 
methods defined in all these classes rather than having a separate 
class for them. 
 Utility operations: All the new Date Time API classes comes with 
methods to perform common tasks, such as plus, minus, format, 
parsing, getting separate part in date/time etc. 
 Extendable: The new Date Time API works on ISO-8601 calendar 
system but we can use it with other non ISO calendars as well. 
Buddha Java User Group - Hyderabad
Buddha Java User Group - Hyderabad
Sources 
 https://www.youtube.com/watch?v=OIg9lNpMJew 
 http://www.oracle.com/technetwork/articles/java/jf14- 
date-time-2125367.html 
 http://docs.oracle.com/javase/8/docs/api/java/time/fo 
rmat/DateTimeFormatter.html 
 http://www.journaldev.com/2800/java-8-date-time-api- 
example-tutorial-localdate-instant-localdatetime-parse- 
and-format 
Buddha Java User Group - Hyderabad

Weitere ähnliche Inhalte

Was ist angesagt?

Reactive programming using rx java & akka actors - pdx-scala - june 2014
Reactive programming   using rx java & akka actors - pdx-scala - june 2014Reactive programming   using rx java & akka actors - pdx-scala - june 2014
Reactive programming using rx java & akka actors - pdx-scala - june 2014
Thomas Lockney
 
Short history of time - Confitura 2013
Short history of time - Confitura 2013Short history of time - Confitura 2013
Short history of time - Confitura 2013
nurkiewicz
 
Scalable Realtime Analytics with declarative SQL like Complex Event Processin...
Scalable Realtime Analytics with declarative SQL like Complex Event Processin...Scalable Realtime Analytics with declarative SQL like Complex Event Processin...
Scalable Realtime Analytics with declarative SQL like Complex Event Processin...
Srinath Perera
 
Scala like distributed collections - dumping time-series data with apache spark
Scala like distributed collections - dumping time-series data with apache sparkScala like distributed collections - dumping time-series data with apache spark
Scala like distributed collections - dumping time-series data with apache spark
Demi Ben-Ari
 

Was ist angesagt? (20)

Thinking Functionally with Clojure
Thinking Functionally with ClojureThinking Functionally with Clojure
Thinking Functionally with Clojure
 
Intro to Functional Programming with RxJava
Intro to Functional Programming with RxJavaIntro to Functional Programming with RxJava
Intro to Functional Programming with RxJava
 
Reactive programming using rx java & akka actors - pdx-scala - june 2014
Reactive programming   using rx java & akka actors - pdx-scala - june 2014Reactive programming   using rx java & akka actors - pdx-scala - june 2014
Reactive programming using rx java & akka actors - pdx-scala - june 2014
 
Real-time driving score service using Flink
Real-time driving score service using FlinkReal-time driving score service using Flink
Real-time driving score service using Flink
 
Short history of time - Confitura 2013
Short history of time - Confitura 2013Short history of time - Confitura 2013
Short history of time - Confitura 2013
 
Performance van Java 8 en verder - Jeroen Borgers
Performance van Java 8 en verder - Jeroen BorgersPerformance van Java 8 en verder - Jeroen Borgers
Performance van Java 8 en verder - Jeroen Borgers
 
Reactive programming with RxJava
Reactive programming with RxJavaReactive programming with RxJava
Reactive programming with RxJava
 
Predictive Maintenance with Deep Learning and Apache Flink
Predictive Maintenance with Deep Learning and Apache FlinkPredictive Maintenance with Deep Learning and Apache Flink
Predictive Maintenance with Deep Learning and Apache Flink
 
Reactive Programming and RxJS
Reactive Programming and RxJSReactive Programming and RxJS
Reactive Programming and RxJS
 
Date class
Date classDate class
Date class
 
Stream analysis with kafka native way and considerations about monitoring as ...
Stream analysis with kafka native way and considerations about monitoring as ...Stream analysis with kafka native way and considerations about monitoring as ...
Stream analysis with kafka native way and considerations about monitoring as ...
 
A More Scaleable Way of Making Recommendations with MLlib-(Xiangrui Meng, Dat...
A More Scaleable Way of Making Recommendations with MLlib-(Xiangrui Meng, Dat...A More Scaleable Way of Making Recommendations with MLlib-(Xiangrui Meng, Dat...
A More Scaleable Way of Making Recommendations with MLlib-(Xiangrui Meng, Dat...
 
Akka-demy (a.k.a. How to build stateful distributed systems) I/II
 Akka-demy (a.k.a. How to build stateful distributed systems) I/II Akka-demy (a.k.a. How to build stateful distributed systems) I/II
Akka-demy (a.k.a. How to build stateful distributed systems) I/II
 
Java calendar
Java calendarJava calendar
Java calendar
 
JEEConf 2016. Effectiveness and code optimization in Java applications
JEEConf 2016. Effectiveness and code optimization in  Java applicationsJEEConf 2016. Effectiveness and code optimization in  Java applications
JEEConf 2016. Effectiveness and code optimization in Java applications
 
Scalable Realtime Analytics with declarative SQL like Complex Event Processin...
Scalable Realtime Analytics with declarative SQL like Complex Event Processin...Scalable Realtime Analytics with declarative SQL like Complex Event Processin...
Scalable Realtime Analytics with declarative SQL like Complex Event Processin...
 
Scala like distributed collections - dumping time-series data with apache spark
Scala like distributed collections - dumping time-series data with apache sparkScala like distributed collections - dumping time-series data with apache spark
Scala like distributed collections - dumping time-series data with apache spark
 
Calendar class in java
Calendar class in javaCalendar class in java
Calendar class in java
 
Ds practical file
Ds practical fileDs practical file
Ds practical file
 
Streaming Data Flow with Apache Flink @ Paris Flink Meetup 2015
Streaming Data Flow with Apache Flink @ Paris Flink Meetup 2015Streaming Data Flow with Apache Flink @ Paris Flink Meetup 2015
Streaming Data Flow with Apache Flink @ Paris Flink Meetup 2015
 

Andere mochten auch

Andere mochten auch (20)

Lambda expressions java8 - yousry
Lambda expressions java8 - yousryLambda expressions java8 - yousry
Lambda expressions java8 - yousry
 
Java8 Lambda and Streams
Java8 Lambda and StreamsJava8 Lambda and Streams
Java8 Lambda and Streams
 
Exploring Streams and Lambdas in Java8
Exploring Streams and Lambdas in Java8Exploring Streams and Lambdas in Java8
Exploring Streams and Lambdas in Java8
 
Boost your craftsmanship with Java 8
Boost your craftsmanship with Java 8Boost your craftsmanship with Java 8
Boost your craftsmanship with Java 8
 
Java8
Java8Java8
Java8
 
Java8 Neue Sprachfeatures - Lambda/Streams/default Methods/FunctionalInterfaces
Java8 Neue Sprachfeatures - Lambda/Streams/default Methods/FunctionalInterfacesJava8 Neue Sprachfeatures - Lambda/Streams/default Methods/FunctionalInterfaces
Java8 Neue Sprachfeatures - Lambda/Streams/default Methods/FunctionalInterfaces
 
Why is Java relevant? New features of Java8
Why is Java relevant? New features of Java8 Why is Java relevant? New features of Java8
Why is Java relevant? New features of Java8
 
Java8: what's new and what's hot
Java8: what's new and what's hotJava8: what's new and what's hot
Java8: what's new and what's hot
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
 
2014 java functional
2014 java functional2014 java functional
2014 java functional
 
Java8
Java8Java8
Java8
 
Introduction to functional programming with java 8
Introduction to functional programming with java 8Introduction to functional programming with java 8
Introduction to functional programming with java 8
 
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
JDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation streamJDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation stream
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
 
Java8 and Functional Programming
Java8 and Functional ProgrammingJava8 and Functional Programming
Java8 and Functional Programming
 
Java8 features
Java8 featuresJava8 features
Java8 features
 
Functional Java 8 in everyday life
Functional Java 8 in everyday lifeFunctional Java 8 in everyday life
Functional Java 8 in everyday life
 
Java8 training - Class 1
Java8 training  - Class 1Java8 training  - Class 1
Java8 training - Class 1
 
Java8 training - class 2
Java8 training - class 2Java8 training - class 2
Java8 training - class 2
 
Java8 training - class 3
Java8 training - class 3Java8 training - class 3
Java8 training - class 3
 
Java8 - Under the hood
Java8 - Under the hoodJava8 - Under the hood
Java8 - Under the hood
 

Ähnlich wie A Quick peek @ New Date & Time API of Java 8

JAZOON'13 - Sam Brannen - Spring Framework 4.0 - The Next Generation
JAZOON'13 - Sam Brannen - Spring Framework 4.0 - The Next GenerationJAZOON'13 - Sam Brannen - Spring Framework 4.0 - The Next Generation
JAZOON'13 - Sam Brannen - Spring Framework 4.0 - The Next Generation
jazoon13
 
Software Uni Conf October 2014
Software Uni Conf October 2014Software Uni Conf October 2014
Software Uni Conf October 2014
Nayden Gochev
 
Spring 4 on Java 8 by Juergen Hoeller
Spring 4 on Java 8 by Juergen HoellerSpring 4 on Java 8 by Juergen Hoeller
Spring 4 on Java 8 by Juergen Hoeller
ZeroTurnaround
 

Ähnlich wie A Quick peek @ New Date & Time API of Java 8 (20)

Java 8
Java 8Java 8
Java 8
 
Java22_1670144363.pptx
Java22_1670144363.pptxJava22_1670144363.pptx
Java22_1670144363.pptx
 
Stream Api.pdf
Stream Api.pdfStream Api.pdf
Stream Api.pdf
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
 
Java dates
Java datesJava dates
Java dates
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
 
Example Of Import Java
Example Of Import JavaExample Of Import Java
Example Of Import Java
 
Java SE 8 & EE 7 Launch
Java SE 8 & EE 7 LaunchJava SE 8 & EE 7 Launch
Java SE 8 & EE 7 Launch
 
Java- Updates in java8-Mazenet solution
Java- Updates in java8-Mazenet solutionJava- Updates in java8-Mazenet solution
Java- Updates in java8-Mazenet solution
 
Java utility classes
Java utility classesJava utility classes
Java utility classes
 
JAZOON'13 - Sam Brannen - Spring Framework 4.0 - The Next Generation
JAZOON'13 - Sam Brannen - Spring Framework 4.0 - The Next GenerationJAZOON'13 - Sam Brannen - Spring Framework 4.0 - The Next Generation
JAZOON'13 - Sam Brannen - Spring Framework 4.0 - The Next Generation
 
Software Uni Conf October 2014
Software Uni Conf October 2014Software Uni Conf October 2014
Software Uni Conf October 2014
 
55 New Features in Java SE 8
55 New Features in Java SE 855 New Features in Java SE 8
55 New Features in Java SE 8
 
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
 
Spring 4 on Java 8 by Juergen Hoeller
Spring 4 on Java 8 by Juergen HoellerSpring 4 on Java 8 by Juergen Hoeller
Spring 4 on Java 8 by Juergen Hoeller
 
Java interview questions and answers
Java interview questions and answersJava interview questions and answers
Java interview questions and answers
 
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsIntroduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
 
Spring Framework 4.0 - The Next Generation - Soft-Shake 2013
Spring Framework 4.0 - The Next Generation - Soft-Shake 2013Spring Framework 4.0 - The Next Generation - Soft-Shake 2013
Spring Framework 4.0 - The Next Generation - Soft-Shake 2013
 
Jakarta EE and MicroProfile - EclipseCon 2020
Jakarta EE and MicroProfile - EclipseCon 2020Jakarta EE and MicroProfile - EclipseCon 2020
Jakarta EE and MicroProfile - EclipseCon 2020
 
2014 10 java 8 major new language features
2014 10 java 8 major new language features2014 10 java 8 major new language features
2014 10 java 8 major new language features
 

Kürzlich hochgeladen

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
ssuserdda66b
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 

Kürzlich hochgeladen (20)

Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 

A Quick peek @ New Date & Time API of Java 8

  • 1. New Date & Time API of Java8 - Buddha Jyothiprasad
  • 2. Agenda  A Quick look at Old API for Date and Time  Discuss the issues with it  Introduce the new API from Java 8  See some examples of various concepts in new API Buddha Java User Group - Hyderabad
  • 3. A Quick Look at old API  java.util.Date  java.sql.Date  Calendar  GregorianCalendar  TimeZone  DateFormat  SimpleDateFormat Some bugs that doesn’t look like Bugs with old API 3 Java User Group - Hyderabad
  • 4. Issues with the old approach Ø Date is actually DateTime Ø Different class for SQL Ø Date doesn’t have timezone Ø getMonth() is zero-based, getYear() is 1900-based (i.e., the year 2009 is represented as 109) Ø Mutable hence not thread-safe by default Ø java.util.Date represents an instant on the timeline but invoking toString() prints time stamp along with time zone, causing confusion among developers Ø Calendar can’t format date directly Ø Arithmetic operations are still tricky Buddha Java User Group - Hyderabad
  • 5. Fixed Code that doesn’t look right Buddha Java User Group - Hyderabad
  • 6. New API  New package java.time  New classes LocalDate, LocalTime  A composite class LocalDateTime  Supports numerous ways of creating Date and Time objects  Supports Truncation, Timezones, Periods, Durations, Chronologies ANSI SQL Java SE 8 DATE LocalDate TIME LocalTime TIMESTAMP LocalDateTime TIME WITH TIMEZONE OffsetTime TIMESTAMP WITH TIMEZONE OffsetDateTime And many more…. 6 Java User Group - Hyderabad
  • 7. Java 8 packages for Date & Time • Consists of major base classes • LocalDate, LocalTime, Instant, Duration java.time • Consists of generic API for non ISO Calendar Systems java.time.chrono • Contains temporal objects to find out specific date/time related like firstDay of month java.time.temporal • Classes for formatting and parsing date time objects java.time.format java.time.zone • Classes for supporting different timezones Buddha Java User Group - Hyderabad
  • 8. Creating Objects  All the core classes are constructed by fluent factory methods  When constructing a value by its constituent fields, the factory is called of  when converting from another type, the factory is called from  There are also parse methods that take strings as parameters  Standard Java getter conventions are used in order to obtain values 8 Java User Group - Hyderabad
  • 9. Code for Creating Date & Time Objects 9 Java User Group - Hyderabad
  • 10. Date & Time manipulation  We can alter the object values in order to perform calculations  All objects are immutable  Setters are no more  New API also has a concept of Adjuster methods  These methods are called with and return new objects  There are also plus adjusters  We can write our own with adjusters and plus adjusters 10 Java User Group - Hyderabad
  • 11. Date Manipulation examples 11 Java User Group - Hyderabad
  • 12. Time Zones  The local classes that we looked at previously abstract away the complexity introduced by time zones  ZonedDateTime is a date and time with a fully qualified time zone  This can resolve an offset at any point in time  Other classes are ZoneId, ZoneOffset, OffsetDateTime, 12OffsetTime Java User Group - Hyderabad
  • 13. Time Zone examples 13 Java User Group - Hyderabad
  • 14. Instant, Periods & Duration  Instant is the closest sibling of java.util.Date. Instant class is used to work with machine readable time format, it stores date time in unix timestamp.  A Period represents a value such as “3 months and 1 day,”  A Duration is a distance on the timeline measured in terms of time, and it fulfills a similar purpose to Period, but with different precision Buddha Java User Group - Hyderabad
  • 15. Code snippets Buddha Java User Group - Hyderabad
  • 16. Parsing & Formatting  Every class in date time formatter has methods for parsing and formatting  format() and parse() directly on the date objects  DateTimeFormatter  Loads of Predefined formatters like ISO_DATE  Custom formats can also be provided via DateTimeFormatter.ofPa ttern() method 16 Java User Group - Hyderabad
  • 17. Parsing & Formatting snippets 17 Java User Group - Hyderabad
  • 18. Query  A TemporalQuery can be used to retrieve information from a temporal-based object  The TemporalQueries class(note the plural) provides several predefined queries  The precision query, for example, returns the smallest ChronoUnit that can be returned by a particular temporal-based object  We can also create custom queries by implementing the interface TemporaryQuery 18 Java User Group - Hyderabad
  • 19. Working with Custom Queries Buddha Java User Group - Hyderabad
  • 20. Legacy Support  Legacy Date/Time classes are used in almost all the applications  Backward compatibility is a must  Following Utility methods are provided for that purpose  toInstant()  toZoneId()  from() 20 Java User Group - Hyderabad
  • 21. Summary  Immutability: All the classes in the new API are immutable hence they are thread-safe.  Separation of Concerns: The new API separates clearly between human readable date time and machine time. It defines separate classes for Date, Time, DateTime, Timestamp etc.  Consistency: The methods are clearly defined and perform the same action in all the classes. There are format() and parse() methods defined in all these classes rather than having a separate class for them.  Utility operations: All the new Date Time API classes comes with methods to perform common tasks, such as plus, minus, format, parsing, getting separate part in date/time etc.  Extendable: The new Date Time API works on ISO-8601 calendar system but we can use it with other non ISO calendars as well. Buddha Java User Group - Hyderabad
  • 22. Buddha Java User Group - Hyderabad
  • 23. Sources  https://www.youtube.com/watch?v=OIg9lNpMJew  http://www.oracle.com/technetwork/articles/java/jf14- date-time-2125367.html  http://docs.oracle.com/javase/8/docs/api/java/time/fo rmat/DateTimeFormatter.html  http://www.journaldev.com/2800/java-8-date-time-api- example-tutorial-localdate-instant-localdatetime-parse- and-format Buddha Java User Group - Hyderabad