Presentation is loading. Please wait.

Presentation is loading. Please wait.

Joda Time and a Brief History of the World

Similar presentations


Presentation on theme: "Joda Time and a Brief History of the World"— Presentation transcript:

1 Joda Time and a Brief History of the World
Daniel Joda Time and a Brief History of the World

2 Preamble

3 Epoch (reference date)
Serves as a reference point from which time is measured. Most of the world uses Anno Domini calendar era (the civil calendar era used internationally and in many countries) Traditionally-reckoned Incarnation of Jesus. Many other current and historical calendar eras exist, each with its own epoch.

4 Asian Epochs Japan: From the accession of the current emperor. China:
Followed same with emperor until 1912. Since 1912: Republican era was established still used in Taiwan Common Era: People's republic of China starts in 1949. India: The Saka Era. Vernal Equinox since year 78. North Korea: Starts 1912: but because Kim Il-Sung was born on that date. Thailand: Founding of Bangkok in 1782, but in 1941 uses 543BC started Thai Solar Calendar.

5 Religious Epochs Israel - Hebrew Calendar dates from "Creation" (Anno Mundi) / March 18, 3952 BC In case you are wondering Earth Day is on Spring Equinox Islam - Anno Hegiræ - The year of the Hijra (the Migration of Mohammed to Medina in 622 Bikram Samwat Calendar established by Indian emperor Vikramaditya. It is a popularly used calendar in India and the official calendar of Bangladesh and Nepal.

6 Already it's complex

7 Computer System Epochs
Matlab, Turbo DB, tdbengine – January 1, 0 Symbian, .NET, RXX, Rata Die – January 1, 1 NTFS, COBOL, Win32/64 – January 1, 1601 MS SQL Server – January 1, 1753 Microsoft Excel, Lotus January 0, 1900. Common LISP, CICS, Network Time Protocol – January 1, 1900 LabView, Mac OS <= 9.0, Palm – January 1, 1904 And More...

8 Perhaps a Standard 0 = January 1, 1970 Midnight GMT. Unix Time
Unix, Linux, Ruby, Mac OS X, Java, JavaScript, C, PHP

9 GMT Greenwich Mean Time
Mean solar time at the Royal Observatory in Greenwich, London. Britain had been the world's time keeper since Victorian Age. It is commonly used in practice to refer to UTC (not accurate) Side Note: GMT used in winter, British Summer Time in summer

10 UTC? Coordinated Universal Time
Backronym: "Universal Time, Coordinated" Time Standard based on International Atomic Time (TAI) Not based on solar calculations UTC replaced GMT as the basis for the main reference time scale or civil time in various regions on 1 January 1972. .

11 ISO 8601 Representation of dates and times is an international standard covering the exchange of date and time-related data. Avoid misinterpretation of numeric representations of dates and times. Standardized method of communicating time- based information across time zones by attaching an offset to Coordinated Universal Time (UTC)

12 How ISO 8601 is Done Date: Separate Date and Time in UTC:  :01Z Combined Date and Time in UTC: T07:01Z Combined Date and Time in MDT: T07:38: :00 Date With Week Number: 2010-W27-3 Ordinal Date: Duration: P3Y6M4DT12H30M5S Intervals: T13:00:00Z/ T15:30:00Z T13:00:00Z/P1Y2M10DT2H30M P1Y2M10DT2H30M/ T15:30:00Z P1Y2M10DT2H30M

13 Modern Calendering/Chronology

14 Julian Reform of the Roman calendar
Was introduced by Julius Caesar in 46 BC Remained in use into the 20th century in some countries as a civil calendar The Roman Catholic Church and Protestant churches have replaced the Julian calendar with the Gregorian calendar. Orthodox Church (with the exception of Estonia and Finland) still use for calculating the dates of moveable feasts.

15 Gregorian Accepted As Civil Calendar Worldwide
Introduced by Pope Gregory XIII Julian calendar system assumes time between vernal equinoxes is days, when in fact it is about 11 minutes less. Signed 24 February 1582.

16 Other In-Use Calendars
Buddhist - One era (the current era), and has a year offset by 543 from the current Gregorian year. Coptic - Based on that used in ancient Egypt. a.k.a. Alexandrian Calendar In use today by the Coptic Orthodox Church and by farmers tracking the seasons in Egypt.

17 Other In-Use Calendars
Ethiopic – Similar to Coptic in use in Ethiopia Gregorian-Julian - Switch from one to the other occurs at a configurable date. The default date is , as defined by Pope Gregory XIII. Islamic - Lunar calendar used in many Muslim countries. Anno Hegiræ

18 Dates, Times, Calendars are Tough

19 The Problem with Java

20 java.util.Date No support for Locale No calendar support
Just a wrapper for # of milliseconds since epoch Deprecated Intended to reflect coordinated universal time (UTC), it may not do so exactly, depending on the host environment of the Java Virtual Machine. A year y is represented by the integer y

21 java.util.Calendar Based on Gregorian Calendar
A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so forth; thus 11 is December. Mutable, You can change the object created without other references knowing about it. Awkward methods Uses static methods Calendar.getInstance() Other Calendars are awkward to extend.

22 Joda Time

23 Joda Time Straight-forward instantiation and methods
ISO 8601 Based, not Gregorian Calendar Has support for other calendar systems if you need it (Julian, Gregorian-Julian, Coptic, Buddhist) Includes classes for date times, dates without times, times without dates, intervals and time periods. Advanced formatting Well documented and well tested Immutable! Months are 1 based JSR-310

24 Starting off import org.joda.time.DateTime;
DateTime dateTime = new DateTime(); DateTime dt = new DateTime            (" T23:39: :00");

25 Instant Moment in the DateTime continuum specified as a number of milliseconds from T00:00Z Represented by the ReadableInstant interface Instant, DateTime, MutableDateTime and DateTimeMidnight

26 Interval Interval of time from one instant to another instant. Both instants are fully specified instants in the DateTime continuum, complete with time zone. Start instant is inclusive but the end instant is exclusive Interval and MutableInterval

27 Interval Example DateTime saleStart = new DateTime (2011, 11, 26, 5, 30, 0, 0); DateMidnight saleEnd = new DateMidnight(2011, 12, 25); Interval interval = new Interval(saleStart, saleEnd); interval.contains(new DateTime()); //false interval.contains(new DateTime (2011, 12, 12, 20, 12, 44, 332)); //true interval.toDuration().getStandardSeconds(); //Woohoo! sec. sale! Wait what? interval.toPeriod(PeriodType.days()).getDays()); //28 day sale!

28 Duration Duration of time measured in milliseconds
Usually obtained from Interval Start to Finish instant + duration = instant

29 Duration Example DateTime saleStart = new DateTime (2011, 11, 26, 5, 30, 0, 0); DateMidnight saleEnd = new DateMidnight(2011, 12, 25); Interval interval = new Interval(saleStart, saleEnd); interval.contains(new DateTime()); //false interval.contains(new DateTime (2011, 12, 12, 20, 12, 44, 332)); //true interval.toDuration().getStandardSeconds(); //Woohoo! sec. sale! Wait what? interval.toPeriod(PeriodType.days()).getDays()); //28 day sale!

30 Period instant + period = instant
Period of time defined in terms of fields, for example, 3 years 5 months 2 days and 7 hours Differs from a duration in that it is inexact in terms of milliseconds Periods are useful for human interaction “How many weeks will it take?”

31 Period Side Effects Given 1 month period, if you add this period to the 1st February (ISO) then you will get the 1st March. Given 1 month period to the 1st March you will get the 1st April

32 More Period Side Effects
Adding 1 day at the daylight savings boundary. If you use a period to do the addition then either 23 or 25 hours will be added as appropriate. If you had created a duration equal to 24 hours, then you would end up with the wrong result (maybe) Period, Mutable Period

33 Period Example DateTime saleStart = new DateTime (2011, 11, 26, 5, 30, 0, 0); DateMidnight saleEnd = new DateMidnight(2011, 12, 25); Interval interval = new Interval(saleStart, saleEnd); interval.contains(new DateTime()); //false interval.contains(new DateTime (2011, 12, 12, 20, 12, 44, 332)); //true interval.toDuration().getStandardSeconds(); //Woohoo! sec. sale! Wait what? interval.toPeriod(PeriodType.days()).getDays()); //28 day sale!

34 Partial partial + missing fields + time zone = instant
Partial representation of date / time A partial does not fully specify a single point in the datetime continuum Essentially an date or time object to be defined later. LocalDate, LocalTime, LocalDateTime, YearMonth, MonthDay, Partial

35 Partial Example LocalDate localDate = new LocalDate(2011, 10, 11); //LocalDate is not time zone or time specific localDate.minusDays(10).dayOfWeek().getAsText(); //Saturday LocalTime lunch = new LocalTime(11, 30); //Local Time is not time zone or date specific DateTime lunchTime = localDate.toDateTime (lunch,DateTimeZone.forID("US/Mountain")); //Bring it together T11:30: :00

36 Chronology Representation of Calendars Default is ISO Chronology
Pluggable Chronology coptic = CopticChronology.getInstance();

37 Time Zones DateTimeZone zone = DateTimeZone.forID("Europe/London");
DateTimeZone zoneUTC = DateTimeZone.UTC; DateTimeZone zoneUTC =    DateTimeZone.forOffsetHours(hours); Based on public TZ

38 Packaging The public packages are the root package (under org.joda.time) and the format package The private packages are the base, chrono, convert, field and tz packages.

39 JDK interoperability

40 java.util.Date // from JodaTime to JDK DateTime dt = new DateTime();
Date jdkDate = dt.toDate(); // from JDKTime to Joda dt = new DateTime(jdkDate);

41 java.util.Calendar // from Joda to JDK DateTime dt = new DateTime();
Calendar jdkCal =    dt.toCalendar(Locale.CHINESE); // from JDK to Joda dt = new DateTime(jdkCal);

42 java.util.GregorianCalendar
// from Joda to JDK DateTime dt = new DateTime(); GregorianCalendar jdkGCal =      dt.toGregorianCalendar(); // from JDK to Joda dt = new DateTime(jdkGCal);

43 Date and Field Separation
DateTimeField is separate from DateTime to query information. Done through DateTime.Property DateTime.Property has then other methods to do get better information

44 Date and Field Example Given: DateTime dateTime = new DateTime(2011, 7, 12, 20, 0, 0, 0); DateTime.Property dayOfWeekProperty =     dateTime.dayOfWeek(); dayOfWeekProperty.getAsShortText();        //returns "Mon", "Tue", etc. dayOfWeekProperty.getAsText();        // returns "Monday",        // "Tuesday", etc.

45 Date and Field Separation (Cont.)
dayOfWeekProperty.getAsText (Locale.FRENCH); // returns "Lundi", etc. dayOfWeekProperty.get(); // Integer Representation Other metadata on the minimum and maximum text size, leap status, related durations.

46 “Modifying” DateTimes
Given: DateTime dateTime = new DateTime(2011, 7, 12, 20, 0, 0, 0); DateTime result =     dt.dayOfWeek().addToCopy(3); // :00:00.000 DateTime result = dateTime.plusDays(3) // :00:00.000 Each provides a copy

47 Mutable DateTime MutableDateTime mdt = dt.toMutableDateTime();
(Intended for creation purposes) MutableDateTime mdt =     dt.toMutableDateTime();       // perform various calculations on mdt DateTime result =     mdt.toDateTime(); //lock it up!

48 Time Zones // get current moment in default time zone DateTime dt = new DateTime(); // T13:23: :00 // translate to Eastern time DateTime dtEastern = dt.withZone (DateTimeZone.forID("US/Eastern")); // T15:23: :00 DateTime dtEastern = dt.withZoneRetainFields (DateTimeZone.forID("US/Eastern")); // T13:23: :00

49 DateTimeFormatter Used to format the DateTime Instant
DateTimeFormatter fmt =    DateTimeFormat.forPattern("yyyyMMdd"); DateTimeFormatter frenchFmt =    fmt.withLocale(Locale.FRENCH); DateTimeFormatter dateTimeFormatter = ISODateTimeFormat. dateHourMinuteSecond();

50 Direct Format via toString()
DateTime dt = new DateTime(); String a = dt.toString(); String b = dt.toString("dd:MM:yy"); String c = dt.toString ("EEE", Locale.FRENCH); DateTimeFormatter fmt = ...; String d = dt.toString(fmt);

51 What's Possible dateTime.plusDays(20). plusMonths(2).dayOfWeek(). withMaximumValue().plusHours(4). toString ("E MM/dd/yyyy HH:mm:ss.SSS"); Immutability = Automatic Memento

52 Joda-Time Language Libraries
Scala-Time DateTime.nextMonth < DateTime.now + 2.months Clj-Time (hour (date-time ))

53 Testing with JodaTime // always return the same time // when querying current time DateTimeUtils.setCurrentMillisFixed(millis) ; // offset the real time DateTimeUtils.setCurrentMillisOffset (millis); // reset it back DateTimeUtilssetCurrentMillisSystem()

54 Time Pro Tips Have a Continuous Integration Server in another time zone Store Date/Time in Unix Time UTC, Make it your standard Think of Time Zones as presentation specific Different computers have different times due to temperature, incorrectness, adjustment, gravity, and more. Use Joda Time

55 Thank You


Download ppt "Joda Time and a Brief History of the World"

Similar presentations


Ads by Google