Joda-Time & JSR 310 – Problems, Concepts and Approaches

5,529 views

Published on

* Using Date, Calendar and existing date-related APIs can be error-prone, painful and tedious.
* The complexities of accurate timekeeping are beyond your imagine.
* What do you need? Computer-related times or human-related times?
* Need to manipulate dates and times? Using Joda-Time or JSR310 to make it easy!

你可以在以下鏈結找到中文介紹:
http://www.codedata.com.tw/java/jodatime-jsr310-1-date-calendar/

Published in: Technology, Education
0 Comments
12 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
5,529
On SlideShare
0
From Embeds
0
Number of Embeds
1,218
Actions
Shares
0
Downloads
115
Comments
0
Likes
12
Embeds 0
No embeds

No notes for slide

Joda-Time & JSR 310 – Problems, Concepts and Approaches

  1. 1. Joda-Time & JSR 310 – Problems, Concepts and Approaches Justin Lin caterpillar@openhome.cc http://openhome.cc
  2. 2. Agenda • Date and Calendar Problems • Time ABC • Joda-Time • JSR310 2 / 66
  3. 3. 3 / 66
  4. 4. What's wrong? • I am 818 years old? Rounding off error 4 / 66
  5. 5. Fixed • I am 38 years old. There's a long type. All other operands are promoted. 5 / 66
  6. 6. • Taiwan Java Developer Day is 1913/9/2? What's wrong? Deprecated 6 / 66
  7. 7. • Taiwan Java Developer Day is 2013/9/2? What's wrong? This calendar field begins from 0. 7 / 66
  8. 8. • Taiwan Java Developer Day is 2013/8/2. Fixed Use the constant variable of Calendar. 8 / 66
  9. 9. • Days between two calendars is zero? What's wrong? The Calendar instance is mutable and state-reserved. 9 / 66 0
  10. 10. Fixed clone() the instance , or create a new instance. 10 / 66
  11. 11. The Date instance is not a date • It represents a specific instant in time, with millisecond precision. – For example, 1375430498832 milliseconds after "the epoch", namely January 1, 1970, 00:00:00 UTC. 11 / 66
  12. 12. • Prior to JDK 1.1, It allowed the interpretation of dates as year, month, day, hour, minute, and second values. But…wired values… – A year y is represented by the integer y - 1900. – A month, hour, minutes and second begin from 0. – A day of month begins from 1. 12 / 66
  13. 13. • All those methods about the interpretation of dates are deprecated after JDK 1.1. • The setTime method is not deprecated. The Date instance is mutable. • Converting between a specific instant in time manually is error-prone. The Calendar class provides methods for that. But … The Date instance is not a specific instant 13 / 66
  14. 14. • A set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on. – A month, hour, minute and second begin from 0. – Remember to use Calendar.JANUARY. • The Calendar instance is mutable. Methods such as add, set and roll changes the state of the instance. Using Calendar can be painful and tedious 14 / 66
  15. 15. 15 / 66
  16. 16. Time the time • Greenwich Mean Time(GMT) – Originally referred to the mean solar time at the Royal Observatory in Greenwich, London. – Noon Greenwich Mean Time is the moment when the sun reaches its highest point in the sky. – GMT is sometimes used loosely and arguably as a synonym for UTC. • Universal Time(UT) – Observe stars as they crossed a meridian. – In 1935, the term Universal Time was recommended as a more precise term than Greenwich Mean Time. – GMT is the same as UT before 1972. 16 / 66
  17. 17. • International Atomic Time(TAI) – The SI( International System of Units) second was defined in terms of the caesium atom in 1967. – Synchronised with Universal Time at the beginning of 1958. • Coordinated Universal Time(UTC) – Based on TAI. Introduced on at the beginning 1972. – With leap seconds added at irregular intervals to compensate for the slowing of Earth's rotation. – Since 30 June 2012 when the last leap second was added, TAI has been exactly 35 seconds ahead of UTC. 17 / 66
  18. 18. • Unix time – A system for describing instants in time. – Defined as the number of seconds that have elapsed since 00:00:00 UTC on 1 January 1970, not counting leap seconds. • The epoch(date) – An instant in time chosen as the origin of a particular era. – The Unix epoch is the time 00:00:00 UTC on 1 January 1970. 18 / 66
  19. 19. Chronologies • Julian calendar – A reform of the Roman calendar introduced by Julius Caesar in 46 BC, took effect in 45 BC, and widely used from about 4CE to 1582CE. – Defines a leap year as once every four years. • Gregorian calendar – A reform of the Julian calendar. – The last day of the Julian calendar was Thursday, 4 October 1582. – Friday, 15 October 1582 was the first day of the Gregorian calendar. 19 / 66
  20. 20. • Gregorian calendar (continued) – Britain and the British Empire (including the eastern part of what is now the United States) adopted the Gregorian calendar in 1752. 20 / 66
  21. 21. • Gregorian calendar (continued) – The concrete subclass GregorianCalendar of Calendar is a hybrid calendar that supports both the Julian and Gregorian calendar systems. – setGregorianChange sets the Gregorian Calendar change date. Default is October 15, 1582 (Gregorian). 21 / 66 Fri Oct 15 1582 Thu Oct 4 1582
  22. 22. • The ISO8601 standard – An international standard covering the exchange of date and time-related data. – Provide an unambiguous and well-defined method of representing dates and times. • yyyy-mm-ddTHH:MM:SS.SSS • yyyy-dddTHH:MM:SS.SSS • yyyy-Www-dTHH:MM:SS.SSS • ... 22 / 66
  23. 23. • The ISO8601 standard (continued) – When representing dates and times, the Gregorian and ISO8601 differ slightly. – In ISO8601, "19" refer to the century from 1900 to 1999 inclusive. – In Gregorian, the 19th century is 1801 to 1900 inclusive. From: https://en.wikipedia.org/wiki/ISO_8601 23 / 66
  24. 24. Time Zones • A region that has a uniform standard time for legal, commercial, social, and political purposes. • Most of the time zones on land are offset from UTC (UTC−12 to UTC+12) – A time change of one hour is required for each change of longitude by 15°. – The UTC time zone is sometimes denoted by Z. 24 / 66
  25. 25. • Some countries, such as China and India, use a single time zone. https://upload.wikimedia.org/wikipedia/commons/a/ad/Standard_time_zones_of_the_world.png 25 / 66
  26. 26. • Some higher latitude countries use daylight saving time (summer time) for part of the year, typically by changing clocks by an hour. • Taiwan DST were from 1945 to 1961 and 1974 to 1975. 26 / 66
  27. 27. • JDK time zone data is updated when the JDK is updated. • Timezone Updater Tool (aka TZUpdater) – http://www.oracle.com/technetwork/java/javase/ downloads/tzupdater-download-513681.html 27 / 66
  28. 28. Joda-Time
  29. 29. Joda-Time • Created in 2002. • Released as v1.0 in 2005. • Released as v2.0 In 2011. • Currently v2.2. Stephen Colebourne 29 / 66
  30. 30. Key concepts • Instant – Defined as an instant in the datetime continuum specified as a number of milliseconds from 1970-01-01T00:00Z. • The ReadableInstant defines an instant in the datetime continuum. – Instant – DateTime – DateMidnight – MutableDateTime 30 / 66 Immutable
  31. 31. • Instant (continued) – The millisecond instant can be converted to any date time field using a Chronology. Instant Time-line 31 / 66
  32. 32. • Partial – A partial date and time representation. – May 26 could apply to any year. 13:06 p.m. could apply to any day of any year. • The ReadablePartial interface defines a partial time. – LocalDate、LocalTime、LocalDateTime – YearMonth、MonthDay – Partial – YearMonthDay – TimeOfDay 32 / 66
  33. 33. • Partial (continued) Instant Time-line = Partial + missing fields + time zone 33 / 66
  34. 34. • Interval – An interval of time between two instants. • Interval is defined by the ReadableInterval interface. – Interval – MutableInterval 34 / 66
  35. 35. • Interval (continued) Start instant End instant Interval 35 / 66
  36. 36. • Duration – Represents a duration of time measured in milliseconds. • Duration is represented by the ReadableDuration interface. – Duration instant + Duration = instant 36 / 66
  37. 37. • Period – Represents the same concept as Duration, but in "human" terms such as years, months, and weeks. • Period is represented by the ReadablePeriod interface. – Period – MutablePeriod – Years、Months、Weeks、Days – Hours、Minutes、Seconds 37 / 66
  38. 38. • Period (continued) instant + Period = instant 38 / 66
  39. 39. • Chronology – A chronology is a pluggable calendar system. • The Chronology class provides access to the individual date time fields. – ISO8601 (Default) - ISOChronology – Gregorian - GregorianChronology – GregorianJulian – GJChronology – Julian - JulianChronology – Buddhist - BuddhistChronology – Coptic - CopticChronology – Ethiopic - EthiopicChronology – Islamic - IslamicChronology GregorainCalendar replacement 39 / 66
  40. 40. • Chronology (continued) 40 / 66
  41. 41. • Time Zone – Joda-Time also compiles the time zone data into our jar file. – You can update the raw data and recompile the jar at any time. – http://joda-time.sourceforge.net/tz_update.html • Available Time Zones – http://joda-time.sourceforge.net/timezones.html 41 / 66
  42. 42. Beef • What do you need? • Period between two Instants or Partials. 42 / 66
  43. 43. • What do you need? • Most of the time, we need Partial. 43 / 66
  44. 44. • What do you need? • Period. 44 / 66
  45. 45. • Adding 5 days, 6 months, and 3 weeks to a date and printing the formatted result. • Using Joda-Time. 45 / 66
  46. 46. 46 / 66 JS R 31 0
  47. 47. Joda-Time as JSR-310? • Why JSR-310 isn't Joda-Time – http://blog.joda.org/2009/11/why-jsr-310-isn- joda-time_4941.html • Joda-Time has design flaws – Human/Machine timelines – Pluggable chronology – Nulls – Internal implementation Stephen Colebourne 47 / 66
  48. 48. Machine/Human timelines • Machines have one view - a single, ever increasing number. • Humans have a totally different view of time. – Calendar systems. – Years, months, days, hours, minutes and seconds. – Time zones – ... • In Joda-Time, the DateTime class (human view of an instant in time) are implementations of ReadableInstant. This is wrong. 48 / 66
  49. 49. JSR 310 • The java.time package. • The distinction between computer-related times and human-related times have been made more apparent. 49 / 66
  50. 50. Computer-related times • Instant – Represents a fixed point in time as an offset from the standard Java epoch (1st Jan 1970). The instant is stored to nanosecond resolution. – Defines its own time-scale, the Java Time-Scale. – http://download.java.net/jdk8/docs/api/java/time /Instant.html 50 / 66
  51. 51. Human-related times • Without a time-zone in the ISO-8601 – LocalDateTime – LocalDate – LocalTime • Years, months, days – Year, such as 2007. – YearMonth, such as 2007-12. – MonthDay, such as 12-03. 51 / 66
  52. 52. An amount of time • A time-based amount of time. – Duration, such as '34.5 seconds'. –Uses nanosecond resolution with a maximum value of the seconds that can be held in a long. • A date-based amount of time – Period, such as '2 years, 3 months and 4 days'. 52 / 66
  53. 53. Joda-Time vs JSR310 • Joda-Time • JSR310 53 / 66
  54. 54. • Joda-Time • JSR310 54 / 66
  55. 55. • Joda-Time • Using JSR310. 55 / 66
  56. 56. • OffsetDateTime adds to the instant the offset from UTC in ISO-8601. • ZonedDateTime adds full time-zone rules 56 / 66
  57. 57. Framework-level API • The java.time.temporal package. • TemporalAccessor – Defines read-only access to a temporal object, such as a date, time, offset or some combination of these. • Temporal extends TemporalAccessor. – The base interface type for date, time and offset objects that are complete enough to be manipulated using plus, minus and with. 57 / 66
  58. 58. • Temporal implementations. – Instant – LocalDate、LocalDateTime、LocalTime – OffsetDateTime、OffsetTime – Year、YearMonth – ZonedDateTime • MonthDay implements TemporalAccessor rather than Temporal. Why? – http://download.java.net/jdk8/docs/api/java/time/M onthDay.html 58 / 66
  59. 59. • plus and minus of Temporal – plus(TemporalAmount amount) – plus(long amountToAdd, TemporalUnit unit) – minus(TemporalAmount amount) – minus(long amountToSubtract, TemporalUnit unit) • TemporalAmount defines an amount of time, such as "6 hours", "8 days" or "2 years and 3 months". – Duration – Period 59 / 66
  60. 60. • TemporalUnit defines a unit of date-time, such as Days or Hours. 60 / 66
  61. 61. • with of Temporal – with(TemporalField field, long newValue) – with(TemporalAdjuster adjuster) • TemporalField defines a field of date-time, such as month-of-year or hour-of-minute. • Use TemporalAdjuster for more complex alterations 61 / 66
  62. 62. Chronology? • What is the range of values returned by this method in Joda-Time? • The answer is not 1 to 12, but could be 1 to 13! – The Coptic chronology has 13 months in a year, and thus can return a range of 1 to 13. • Most users of the API never check to see if the chronology is the standard ISO chronology. 62 / 66
  63. 63. • A better solution would be to keep the date/time classes restricted to a single calendar system. • Those date and time classes located in the java.time package are in the ISO-8601 calendar system. • Check the java.time.chrono package if you need other chronologies. – JapaneseChronology – ThaiBuddhistChronology – … 63 / 66
  64. 64. Summery • Using Date, Calendar and existing date- related APIs can be error-prone, painful and tedious. • The complexities of accurate timekeeping are beyond your imagine. • What do you need? Computer-related times or human-related times? • Need to manipulate dates and times? Using Joda-Time or JSR310 to make it easy! 64 / 66
  65. 65. • Other libraries for handling dates and times – Date4j, Simple Alternative To java.util.Date. – Arrow, Better dates and times for Python. – Moment.js, A JavaScript date library for parsing, validating, manipulating, and formatting dates. – Noda-Time, A port of Joda-Time to .NET 65 / 66
  66. 66. References • Joda-Time – http://joda-time.sourceforge.net/ • Joda-Time - You can't escape time. Why not make it easy? – http://www.ibm.com/developerworks/java/library/j- jodatime/index.html • JSR 310 Date and Time API for Java – http://www.infoq.com/news/2010/03/jsr-310 • Why JSR-310 isn't Joda-Time – http://blog.joda.org/2009/11/why-jsr-310-isn-joda- time_4941.html • JDK8 Javadoc – http://download.java.net/jdk8/docs/api/index.html 66 / 66

×