Discussions

Industry news: JSR-310 date and time API early draft review

  1. The JSR-310 API entered early draft review (a formal JCP stage) on 2010-02-26. The purpose of this stage is to get as much feedback as possible to ensure the API is fully usable. The review materials are available at http://wiki.java.net/bin/view/Projects/DateTimeEDR1. They include a simple specification, a more detailed user guide, the javadoc and a reference implementation. Feedback can be added to this thread (which will be monitored for the next month) and on the wiki linked above. Alternatively, sign up to the mailing list and follow the open specification that way. Please note that the API is not "finished". Work is still ongoing, so all feedback is extremely useful, and will be listened to. Remember, Java SE already has two poor quality date/time APIs. We need to ensure that the third one works well.

    Threaded Messages (55)

  2. Good to see that this JSR is taking off again. Is this slated for JDK 1.7?
  3. Good to see that this JSR is taking off again. Is this slated for JDK 1.7?
    Whether this is included depends entirely on OracleSun, subject to its completion.
  4. What is the relation to existing java.util.Date java.sql.Date ? How about persistence (eg. hibernate) ? I did not found it in specification.
  5. Obviously my personal opinion here... People will look to replace java.util.Date with one of LocalDate, LocalDateTime, OffsetDate, OffsetDateTime... depending on whether you want timezone information and if you want a date with or without time. java.sql.Date and java.sql.Timestamp will still be used when you write JDBC code (until the JDBC api adds support for these new types). Persistence layers like Hibernate (and Ebean :) etc) will automatically convert between the JDBC types and your 'logical' types (LocalDate, LocalDateTime, OffsetDate, OffsetDateTime) for you - no worries there.
  6. How about persistence (eg. hibernate) ? I did not found it in specification.
    As far as DataNucleus is concerned we can support persistence of such types by addition of a simple plugin for the primary types being added here, and that would allow persistence to all of RDBMS, ODBMS, XML, Excel, ODF, HBase, GAE/J, Amazon S3 etc; the benefits of having an architecture that permits such plugins. No doubt such types would be added to the JDO/JPA specs at convenient points too; I don't see it as a requirement on this JSR to define how they are handled in persistence processes. --Andy (DataNucleus)
  7. Re: Support for persistence[ Go to top ]

    In fact, DataNucleus SVN now has an outline plugin for LocalDate, LocalTime field types --Andy (DataNucleus)
  8. Re: Support for persistence[ Go to top ]

    What is the relation to existing java.util.Date java.sql.Date ? How about persistence (eg. hibernate) ? I did not found it in specification.
    JSR-310 has plans to alter the existing Date and Calendar classes for interation: Date date = new Date(jsr310Instant); Instant jsr310Instant = date.toInstant(); SQL integration is under the control of the JDBC group. They have been following the development of JSR-310. Stephen Colebourne (spec lead)
  9. I was looking at the javadoc. It was not obvious to me what the suggested methods where for converting between types - especially converting to and from java.util.Date. On LocalDateTime I was expecting to find a method like: public static LocalDateTime valueOf(long systemTimeMillis); Is there a plan to add some valueOf methods? Similarly on LocalDateTime I was expecting to find a method that returned a long (like java.util.Date#getTime()):
  10. Re: Type conversion with primitive long[ Go to top ]

    I was looking at the javadoc. It was not obvious to me what the suggested methods where for converting between types - especially converting to and from java.util.Date.

    On LocalDateTime I was expecting to find a method like:

    public static LocalDateTime valueOf(long systemTimeMillis);

    Is there a plan to add some valueOf methods?

    Similarly on LocalDateTime I was expecting to find a method that returned a long (like java.util.Date#getTime()):
    Just curious, why would you ever need to manipulate dates in terms of long? I wonder the need to convert from/to java.util.Date and the new classes, but once you've got a date why do you really need to go down to long? I understand this was necessary for old APIs but can you give a use-case for why it is needed with the new ones? Just curious...
  11. Re: Type conversion with primitive long[ Go to top ]

    ... manipulate dates in terms of long?
    I certainly would not MANIPULATE dates in terms of long ... but we are not going to be able to convert all the existing datetime code overnight. We will need to easily convert to/from the existing types for quite some time. java.util.Date, java.sql.Date and java.sql.Timestamp constructors, System.currentTimeMillis(), Calendar get/setTimeInMillis... all use long. So the use case is ... convert between: long LocalDateTime java.util.Date LocalDate or LocalDateTime etc java.sql.Date LocalDate etc java.sql.Timestamp LocalDateTime etc java.uti.Calendar LocalDateTime etc ... of course you really only need to convert to/from long as all the existing types (java.util.Date, java.sql.Timestamp etc) are easily converted to/from long)
  12. It was not obvious to me what the suggested methods where for converting between types - especially converting to and from java.util.Date.On LocalDateTime I was expecting to find a method like:
    public static LocalDateTime valueOf(long systemTimeMillis);
    Is there a plan to add some valueOf methods?
    Similarly on LocalDateTime I was expecting to find a method that returned a long (like java.util.Date#getTime()):
    The only valid conversion between a LocalDateTime and a Date requires a time zone (LocalDateTime is not a single specific instant on the time-line). As such, a conversion direct from/to a milisecond is undesirable. There are new methods on Date/Calendar that will accept/return an Instant. Stephen Colebourne (spec lead)
  13. Stephen, First of all, thanks for all the great work. I have a few minor API suggestions. I have blogged about them here: http://dushyanthinguva.blogspot.com/2010/03/first-date-sucked-can-second-date-fix_4465.html Thanks, Dushyanth
  14. String.valueOf(...) Boolean.valueOf(...) Double.valueOf(...) Integer.valueOf(...) BigDecimal.valueOf(...) ... LocalDateTime.of(...) To me the static "of" methods look to me like they should be "valueOf" to be consistent with the other types.
  15. String.valueOf(...)
    Boolean.valueOf(...)
    Double.valueOf(...)
    Integer.valueOf(...)
    BigDecimal.valueOf(...)
    ...

    LocalDateTime.of(...)

    To me the static "of" methods look to me like they should be "valueOf" to be consistent with the other types.
    We are using 'of' instead of 'valueOf' because its shorter, particularly wrt the long class names. There are other JDK classes, like EnumSet, that use 'of'. Stephen Colebourne (spec lead)
  16. Dear Sir/Madam, this is not the 1950s. Please make method names readable/obvious. If a high level of brevity were very important, Java would never have been successful. Being serious for a moment: Don't Sun's own guidelines say that method names should be verbs? "of" is not a verb, then again, nor is "value of" - but at least with "value of", there is an implied "get". Best regards, Michael
  17. Agreed. I think EnumSet uses "of" because if it didn't, it'd have to be "valuesOf", if this is the case, then "valueOf" should be used for single values and "of" should be used for collections.
  18. is this really the biggest problem?
  19. is this really the biggest problem?
    Naming conventions help the programmer to understand more quickly what a program does and allow us to use our previous knowledge of past APIs to reason about what methods are most likely to be used in many situations.
  20. We are using 'of' instead of 'valueOf' because its shorter, particularly wrt the long class names. There are other JDK classes, like EnumSet, that use 'of'.

    Stephen Colebourne (spec lead)
    I second the vote to use 'valueOf' instead of 'of'. I think consistency is far more important than brevity.
  21. I don't recall when i last preferred short method names over readabilty and consistency in my own code. An API should rate this even higher.
  22. I wonder if it would be nice to have 2 additional static methods on Instant. // returns now in millis public static Instant currentMillis(); // returns now in nanos public static Instant currentNanos(); e.g. Instant nowMillis = Instant.currentMillis(); // rather than... Instant nowMillis = Instant.millis(System.currentTimeMillis());
  23. // returns now in millis
    public static Instant currentMillis();
    // returns now in nanos
    public static Instant currentNanos();


    e.g.

    Instant nowMillis = Instant.currentMillis();

    // rather than...
    Instant nowMillis = Instant.millis(System.currentTimeMillis());
    With JSR-310, System.currentTimeMillis() should be considered deprecated. The replacement is TimeSource, which has a toInstant() method. There is also the related Clock class. TimeSource.system().toInstant(); We may add a factory: Instant i = Instant.now(TimeSource); to make this obvious. BTW, there is no current access to the time in nanoseconds in the JDK today. The method on System is relative, not absolute wrt the time-line. Stephen Colebourne (spec lead)
  24. I looked for methods to convert between jsr-310 and java.util.concurrent units but could not find any. I think it could be useful.
  25. I looked for methods to convert between jsr-310 and java.util.concurrent units but could not find any. I think it could be useful.
    You are correct, we need to add something to support this. Stephen Colebourne (spec lead)
  26. Looks like instant is still hardwired to the broken simple UTC timescale, instead of TAI or UTC. The notion that the length of a second "effectively varies" in UTC is so fundamentally incorrect that I don't know where to being. The entire point of the 1972 change to UTC was specifically to avoid a non-fixed duration second. POSIX formalized a bug in the old libc routines, and previous JDKs tried to ignore it, but continuing down that path is not a fix. The leapsecond offsets are widely distributed with timezone changes, and don't happen any more frequently or unpredictably than timezone changes. When you get down to the details, people don't treat time as a linear scalar, and pretending that the labels people use have a fixed correlation to a linear time scale is madness. Instant on a fixed linear timescale is fine, and the classes than handle times as collections of fields are also OK. Pretending that you can synthesize a linear timescale from the collection of fields people use to describe is rife with error. Both forms of representation are needed and should co-exist on an equal footing.
  27. Looks like instant is still hardwired to the broken simple UTC timescale, instead of TAI or UTC.
    JSR-310 has a dedicated set of classes to handle time-scales, including TimeScaleInstant. The Instant class uses the "simplified UTC" scale (ignoring leap seconds) because that is what most humans imagine the time-line as (especially true of business domains rather than science domains). Allowing for leap seconds everywhere would make the whole API a lot less friendly in *lots* of places for a marginal use case. The chosen alternative, supporting leap seconds as a marginal use case, balances the needs of most developers with the physical reality. Stephen Colebourne (spec lead)
  28. Examples?[ Go to top ]

    Being a lazy developer, I like to steal (working) examples from JavaDoc rather than try and figure out what methods to use from the user documentation. If you could include at least one or two examples of how each class is used, it's a lot better for lazy developers like me. Stuff like how to use it in a class, e.g. should a date format be a static member variable? is all inferred from the fact that formatters are threadsafe and immutable but it's nice to see best practice in any case.
  29. Some thoughts[ Go to top ]

    Interesting! I like the use of immutable objects and it is certainly an improvement over the current situation, but I think the API can be simplified in some cases. See http://erikwramner.wordpress.com/2010/03/07/thoughts-on-jsr-310 for details.
  30. Re: Some thoughts[ Go to top ]

    The time API is too complex. I think almost 95% of those methods would not be very useful in my programming task. By the way, why the perfix is 'javax', but not 'java'?
  31. Re: javax[ Go to top ]

    The prefix 'javax.time' allows the code to be run in earlier JDKs, such as JDK 1.6. We hope this will aid adoption.
  32. Is there an easy way to get the exact time of DST changes for a given year? Current Java API sorely lacks this.
  33. Is there an easy way to get the exact time of DST changes for a given year?
    Yes. TimeZone zone = TimeZone.of("Europe/London"); // historic transitions for (ZoneOffsetTransition trans : zone.getRules().getTransitions()) { System.out.println("Transition: " + trans); } // future transitions System.out.println("Summer time starts: " + zone.getRules().getTransitionRules().get(0)); System.out.println("Summer time ends: " + zone.getRules().getTransitionRules().get(1));
  34. 2. plus if you depreciated Date class why is it not really taken off yet. Its been there for 12+ years and for last 6 years i have been getting warnign to not use Date class. Ok - we all moved on so please remove it in 1.7 otherwiose there will always be people who would not get it and you will spend too much over the "migration strategies" for such lazy people. its time to cut the cord of Date class - as you had planned. 3. learn from .Net. or visual basic for .Net. They do a good job of date management. 4. Keep simple functions like myDate = Date.toDate(String, "format"); 5. some of the date constants around days and years etc are confusing with some as 0 base and some as 1 base. 6. time zone conversions especially when it comes to GMT are not pretty and there arent examples out there which spell it out. I have to always do a manual calculation and check if the code got it too. its never been simple to understand. 7. day light savings stuff - make if simple enough that people dont have to patch a whole JDK just because US senate voted on it. It should be simpler that inmstalling a patch - and it didnt go smooth last time. it was like Java's Y2K problem. 1. half of issues arround date and time etc in java is its too complex and also no good examples out there. so please provide enough examples and documentation on java doc. Its been a problem with java in general - compare yourself to microsoft MSDN. SUN java docs suck in that sense.
  35. 2. plus if you depreciated Date class why is it not really taken off yet. Its been there for 12+ years and for last 6 years i have been getting warnign to not use Date class. Ok - we all moved on so please remove it in 1.7 otherwiose there will always be people who would not get it and you will spend too much over the "migration strategies" for such lazy people. its time to cut the cord of Date class - as you had planned. 3. learn from .Net. or visual basic for .Net. They do a good job of date management. 4. Keep simple functions like myDate = Date.toDate(String, "format"); 5. some of the date constants around days and years etc are confusing with some as 0 base and some as 1 base. 6. time zone conversions especially when it comes to GMT are not pretty and there arent examples out there which spell it out. I have to always do a manual calculation and check if the code got it too. its never been simple to understand. 7. day light savings stuff - make if simple enough that people dont have to patch a whole JDK just because US senate voted on it. It should be simpler that inmstalling a patch - and it didnt go smooth last time. it was like Java's Y2K problem. 1. half of issues arround date and time etc in java is its too complex and also no good examples out there. so please provide enough examples and documentation on java doc. Its been a problem with java in general - compare yourself to microsoft MSDN. SUN java docs suck in that sense.
  36. The java.util.Date class will not be removed or further deprecated. Oracle/Sun have chosen to not deprecate any more JDK core methods. Dur consideration has been given to other date and time APIs, including .NET. An easier way to format/parse a string will probably be added. JSR-310 uses field values as humans do, indexing from 0 or 1 as appropriate. I hope to produce a detailed page about JSR-310 time zones. JSR-310 currently uses a jar file system for time zones. Simply add/update a jar file on the class path to pick up later zone rules. Stephen Colebourne (spec lead)
  37. Re: make it simple to understand[ Go to top ]

    "plus if you depreciated Date class why is it not really taken off yet. Its been there for 12+ years and for last 6 years i have been getting warnign to not use Date class. " Nothing is ever removed from core Java nor will these deprecated items ever be removed. My understanding is this policy is intended to support backwards compatibility between versions.
  38. Re: make it simple to understand[ Go to top ]

    "plus if you depreciated Date class why is it not really taken off yet. Its been there for 12+ years and for last 6 years i have been getting warnign to not use Date class. "

    Nothing is ever removed from core Java nor will these deprecated items ever be removed. My understanding is this policy is intended to support backwards compatibility between versions.
    Then why deprecate ? Its comon practice to drop "support" after certain years. SUN doesnt support JDK 1.4 anymore. What does that mean then ? Also Oracle itself has changed stuf in core software in last few years. You can go from oracle 7 to 11 g just like that. i dont understand deprecating if its supposed to mean - dont use it as it may be taken off later.
  39. DST changes for 2011[ Go to top ]

    DST changes for 2011 -- not simple.

    http://www.timeanddate.com/time/dst/2011a.html

    http://www.timeanddate.com/time/dst/2011b.html

     

  40. Working with date ranges[ Go to top ]

    Can Mr. Colebourne please provide an example of how you would work with date ranges. For example, what would the code look like to determine whether a date is before, between, or after two other dates. Thanks, -- Marc
  41. Re: Working with date ranges[ Go to top ]

    provide an example of how you would work with date ranges
    if (date1.isBefore(date2)) { // date1 after date 2 } if (date2.isAfter(date2)) { // date2 after date 1 } if (date1.isBefore(date2) == false && date1.isBefore(date3)) { // date1 between date2 and date3 }
  42. Re: Working with date ranges[ Go to top ]

    It's unfortunate that there's still no concept of a date range or time interval in this new API.  That code is very inelegant. 
  43. If there are enums for representing months and days then why have redundant methods? Instead of month.isFebruary() wouldn't month == FEBRUARY be a bit more clear? One thing that should be improved is formatting. I really want to read and write dates in single lines of code (without something as obscure as a DateTimeFormatterBuilder). Apart from this I am really wondering what applications would really benefit from this new JSR. Most applications would be just fine with the current APIs.
  44. If there are enums for representing months and days then why have redundant methods? Instead of month.isFebruary() wouldn't month == FEBRUARY be a bit more clear?
    Well, I believe that most users don't use static imports, so the comparison is to month == MonthOfYear.FEBRUARY. This is quite a bit longer and requires additional effort to code. More significant is that the month.isFebruary() method reads better (more fluent) and code is read far more than it is written.
    One thing that should be improved is formatting. I really want to read and write dates in single lines of code (without something as obscure as a DateTimeFormatterBuilder).
    Something will happen to simplify formatting.
    Apart from this I am really wondering what applications would really benefit from this new JSR. Most applications would be just fine with the current APIs.
    Hmmm. The current Date and Calendar APIs are broken in many, many ways. See the Joda-Time homepage for some ideas how.
  45. If there are enums for representing months and days then why have redundant methods? Instead of month.isFebruary() wouldn't month == FEBRUARY be a bit more clear? One thing that should be improved is formatting. I really want to read and write dates in single lines of code (without something as obscure as a DateTimeFormatterBuilder). Apart from this I am really wondering what applications would really benefit from this new JSR. Most applications would be just fine with the current APIs.
  46. If there are enums for representing months and days then why have redundant methods? Instead of month.isFebruary() wouldn't month == FEBRUARY be a bit more clear? One thing that should be improved is formatting. I really want to read and write dates in single lines of code (without something as obscure as a DateTimeFormatterBuilder). Apart from this I am really wondering what applications would really benefit from this new JSR. Most applications would be just fine with the current APIs.
  47. XMLGregorianCalendar[ Go to top ]

    I don't see support for XMLGregorianCalendar (unless I missed it in the docs, sorry if so). E.g. Prior to JSR-310, if you want to convert an XML date (from schema's date type), AFAIK, you have to call the toGregorianCalendar method on the javax.util.dateType.XMLGregorianCalendar class and then call (say) the getTime method on the java.util.GregorianCalendar class to convert that to a java.util.Date object. Now we have JSR-310, what's different about the above steps?
  48. Re: XMLGregorianCalendar[ Go to top ]

    I don't see support for XMLGregorianCalendar
    We need to add support for conversion here. I'll add this to the TODO. Stephen Colebourne (spec lead)
  49. Why not just use JodaTime?[ Go to top ]

    Why not just copy and paste all of JodaTime as the starting point? JodaTime still seems superior to this JSR if only because it's actually pretty complete and there's a lot of nice convenience classes to do a bunch of stuff on one line.
  50. Why not just copy and paste all of JodaTime as the starting point? 
    See http://www.jroller.com/scolebourne/entry/why_jsr_310_isn_t
  51. Duration and Period seem to be interchangable. I understand that Duration is meant for machines and Period for human consumption. However, while there is a way to convert from Period to Duration, I believe a method to convert from Duration to Period is missing (unless I've missed it). Also it's not quite clear why you would need two classes for this. A human readable format imho is just presentation...
  52. Duration and Period seem to be interchangable. I understand that Duration is meant for machines and Period for human consumption. However, while there is a way to convert from Period to Duration, I believe a method to convert from Duration to Period is missing (unless I've missed it).

    Also it's not quite clear why you would need two classes for this. A human readable format imho is just presentation...
    The concept of 5 months is not just "presentation" on top of a Duration - the duration of 5 months varies depending on what you add it to.

    Equally, the duration of a Duration can vary. This is more subtle, and occurs due to the use of the artificial simplified UTC time scale instead of the pure second based scale of TAI.

    We may need more methods to convert between the classes.

  53. The purpose of DateAdjuster seems to be to provide small, simple adjustments to dates. I would like a method to combine DateAdjuster's in a compound class to create more complex behavior. So I suggest a method like: DateAdjusters.compound(DateAdjuster... adjusters) - Create a compound DateAdjuster with the array of adjusters.
  54. I suggest a method like:
    DateAdjusters.compound(DateAdjuster... adjusters) - Create a compound DateAdjuster with the array of adjusters.
    This is an interesting idea. I'll think about it :-)
    Stephen Colebourne (spec lead)
  55. A few feature requests[ Go to top ]

    I've read over the spec and I have a few suggestions on what I'd like to see to make it a bit more user friendly. 

    The main problem I have with Date / Calendar is the large number of helper classes that we need to use for basic tasks.  Below are a few methods I'd love to see implemented which, for me, would take care of the 20% of the functionality I use 80% of the time.

    //--------------------- Creation, misc.
    Instant i = Instant.getInstance(); // Equivalent of new Date(), i.e. "NOW"
     
    // Can accept String for time zones (automatically uses TimeZone object within method)
    i.setTimeZone("EST");
     
    // The "toString()" pattern can be set without requiring additional helper classes
    // Many pre-canned patterns should be available (ex. i.setToStringPattern(ORDINAL_DATE);)
    i.setToStringPattern("yyyy-MM-dd hh:mm");
     
    /*--------------------- Time setting
    Time can be set by either [UNIT, amount], or by [pattern, value]
    */
    i.setTime(NANO, 0); // Time is set to 0 nanoseconds following the EPOCH
    i.setTime("yyyy-MM-dd", "2010-01-31");
     
    /*--------------------- Valid and invalid dates
    There are three date modes:
                    STRICT - Only dates which exist are allowed (i.e. Calendar non-lenient) [default value]
                    LENIENT - Dates which don't exist are changed into those that do (i.e. Calendar lenient; April 31 --> May 1)
                    LAX - Dates which can't exist are kept as is, though flagged as invalid (using getTimeInMillis returns the same value as LENIENT)
    */
    i.dateValidityMode(LAX);
     
    i.setTime(MONTH, FEBRUARY); // Sets the month to February, keeps the DAY_OF_MONTH to 31
    i.setTime(WEEK_OF_YEAR, 12); // Keeps month at February, day at 31
     
    i.isValidTime(); // Returns false since it has been set to February 31st, week 12
     
    /*
    If you change the mode to lenient while the the date is invalid, it is converted into a valid date in same order as the operations were used:
    (Jan 31 --[MONTH, 1]--> March 2 --[WEEK_OF_YEAR, 12]--> March 18)
    */
    i.dateValidityMode(LENIENT);
     
    i.dateValidityMode(STRICT);
    i.setTime(MONTH, FEBRUARY);
    i.setTime(DAY_OF_MONTH, 30); // An Exception is thrown here
     
    /*--------------------- Time modifying
     Time can be added / subtracted similar to how it is set
     
     Add time has an optional parameter for how to round invalid times while in STRICT or LENIENT modes
    */
    i.setTime("MM dd", "01 31");
    i.addTime(MONTH, 1, ROUND_UP); // March 1
     
    i.setTime(MONTH, JANUARY);
    i.setTime(DAY_OF_MONTH, LAST); // Sets to the last day of the current month
    i.addTime(MONTH, 1, ROUND_DOWN); // February 28
    i.addTime(MONTH, 1); // March 28
     
    i.setTime("MM dd", "01 31"); i.addTime(MONTH, 1); // If STRICT or LENIENT, throws an Exception
     
    i.setTime("MM dd", "01 31"); i.addTime(MONTH, -1); // December 31 of the previous year
     
    /*------------------------ Time conversion
     
    Straight forward; you should be able to get the Instant object in most other Java date formats
    */
     
    java.util.Date utilDate = i.toDate();
    java.util.Calendar c = i.toCalendar();
    javax.xml.datatype.XMLGregorianCalendar xgc = i.toXMLGregorianCalendar();
    // etc.
  56. A few feature requests[ Go to top ]


    Creation:
    I'll be adding something for now().

    Time zone strings:
    Allowing method arguments as time zone strings greatly extends a large API. At some point convenience methods have to end.

    ToString setting:
    These objects are immutable so I won't be setting the toString() pattern. I'll probably support a toString(pattern) method.

    Construction:
    Both from EPOCH and parsed versions are available.

    Leniency:
    All JSR-310 dates are strict. Lenient parsing is supported.

    Modification:
    See DateResolver for resolving invalid dates.
    See DateAdjuster for altering to the last day-of-month.

    Conversion:
    Methods will be on the target classes.

    Thanks for the detailed ideas.