DateTimeRequests < Projects < TWiki

TWiki . Projects . DateTimeRequests

JSR 310 Date and Time API

This page is designed for all members of the Java community to add requests to the JSR. All ideas are welcome.

Additions may be made using your signature, or anonymously.

Threads and blogs


RFC 2616 date format

A bit of an edge case, but IMHO the text parser should be able to handle the three kinds of HTTP/1.1 dateformat as HTTP is likely to stick around for awhile. Quoting RFC 2616, section 3.3:
  1. Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
  2. Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
  3. Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format
The first two formats are no problem, but the third format prefixes single-digit days with a space rather than a zero to preserve fixed length. This is an uncommon bit of markup that tends to require special attention.

-- BarendGarvelink - 05 Mar 2007


Derivation of Time Zone settings

[Not sure this is in scope.]

At present Java has its own method for determining timezones.

This means that any changes have to be applied to both the OS and Java. Also discrepancies can creep in.

If the OS supports TZ information, then it seems to me that Java should use the OS view.

-- Main.sebbazgm - 10 Mar 2007


Consider some science related time scales

[Not sure this is in scope.]

Currently, time representation in Java is limited to a simplified UTC model and location based timezones. For some scientific applications, this is wrong since leap seconds are ignored and this is also insufficient. An example of wrong behaviour is that the interval between 2005-12-31T23:59:00 and 2006-01-01T00:01:00 was 121 seconds long, not 120 seconds long). There is currently no way to consider the TAI (International Atomic Time), TT (Terrestrial Time), nor GPS time. I don't consider more complex scales such as Geocentric Coordinate Time (TCG) or Barycentric Coordinate Time (TCB) because they are not computed by simple offsets as the previous ones.

Supporting this could be done very simply by providing additional timezones (TAI, TT, GPS and leap-seconds-corrected-UTC). Since most users don't need these refinements, they could simply ignore these timezones they do not know and everything would be backward compatible. These timezones would be helpful for high accuracy and scientific work (space dynamics, oceanography, geodesy, navigation ...) , as well as for embedded devices relying on either GPS, Glonass or Galileo signals or NTP.

The only time dependant offset is the one between TAI and UTC, which changes each time a leap second is introduced. Leap seconds are not introduced very often as the official history file from IERS shows. It would probably be sufficient to consider only the integer offsets starting 1972-01-01. It is also guaranteed that the changes are known several months in advance.

-- Main.luc - 12 Mar 2007

I think this is a good suggestion. -- BarendGarvelink


First day of week

pls consideer an APi to get the first day of week of a selected date, I need ot for making the week view of a calendar, suppose today is "wednesday" i should be able to get the date of the first day of the week that is sunday. -- daljeetsingh


Consider leveraging ISO 19108

This is part of a suite of geospatial standards, but this one only deals with time, and presents only a data model. Interfaces for a portion of this model are defined within the GeoAPI? project (http://geoapi.sourceforge.net/pending/javadoc/org/opengis/temporal/package-summary.html), which could either be leveraged directly or used as a guideline.

This is a considerably more flexible model than "dates" and "calandars". You can define a temporal reference frame to describe the following types of situations:

This specification has temporal geometry (e.g. "points" and "intervals") as well as a way to express temporal topography (e.g. temporal relations: Things B,C and D succeed/replace thing A.)

Last but not least, this is not just a specification, it's an international standard. Unfortunately, this means that developers on this JSR should probably buy it. Fortunately, it's only $30 US. A quality interface implementation with good javadocs should obviate any need for the average Java developer to buy it.

-- Main.bnordgren - 13 Mar 2007


Time Points have different granularity

Different domains and even different problems within a single domain require time points of different granularity. Many things happen at day precision and for many business purposes anything more fine-grained than second precision just does not make any sense. For more technical purposes, I might want millisecond precision or even better.

Fowler has written this up more eloquently than I possibly could: http://www.martinfowler.com/ap2/timePoint.html

Please note that I am explicitly referring to time points, not intervals or periods.

Thanks, Oliver

-- Main.okamps - 24 May 2007

+1. I work in a scientific domain where time events (Instants?) have to be compared with each other. Equipment taking physical timestamped measurements have variable time precision (seconds, millis, nanos) and this has to be taken into account when making comparisons. -- NiallStapley?


DateTimes? from DateTime? minus Duration

As mentioned on the mailing list, it would be cool to be able to simply create a DateTime? from an existing DateTime? plus / minus a Duration - good for getting birth dates for people of a certain age among other things.

It woudl also be useful to be able to do the following:

TimeOfDay? now = TimeOfDay?.currentTime(); then = now.minusMinutes(10); Duration d = now.minus(then);

Thanks, Andrew

-- Main.al94781 - 04 Jun 2007


Date and Time Differences

I think it will be useful if we are able to find out the difference between two date/time objects. Off my head, I can think of one use case: finding out the number of days that has elapsed to compute late-return charges.

Of course, the api should allow us to define the (reasonable) period to compute the difference. For example, using hypothetical api calls, and liberal variable names:

date1.hasSinceElapsed(Days, fromDate); date1.hasSinceElapsed(Hours, fromDate); time1.hasSinceElapsed(Seconds, fromTime);

Thanks, shaolang


Precisely define the addition of DateTime? and Period

For example, what is 7/31-1m1d? In Jode, it's computed as 7/31-1m-1d=6/30-1d=6/29. However, I think the proper answer should be 6/30.

Thanks, Weijun


CalendarDay? today(), tomorrow() and yesterday() methods

An API user must not be able to generate a reference to Today without specifying the TimeZone that they're in. The assumption is that we're using the default TimeZone of the user. However, unless this is made clear to the user, mistakes will creep in.

I would suggest as the method signature: CalendarDay?.today(TimeZone timeZone)

Then, you could add an additional method of today() with Javadoc to explicitly state "this version of today() uses TimeZone.getDefaultTimeZone() to generate today's date. Please use with caution."

-- Main.daveboden - 08 Aug 2007


CalendarDay? getDayOfWeek() - please return an enum not an integer

The getDayOfWeek() method should return an enum rather than an int value. The fact that the day of the week is stored as an integer is an implementation detail. The numbering is arbitrary. Someone is going to do a > b on the day of week values if you give them the opportunity to. This boolean statement is pretty much meaningless, what's the programmer trying to do? Giving programmers an enum is more meaningful: Sunday rather than "1".

-- Main.daveboden - 13 Aug 2007


Other time synchronization options for JVM System time

Setting the JVM's clock (not OS's clock) with a choice of either:

Granted the these requests might be out of the scope of this project, I thought I'd throw them out there for discussion.

-- Main.pdjohe - 09 Sep 2007


Cooperation/recognition of common goals with JSR-275 - Units API

As many have already mentioned, this project should definitely work hand-in-hand with Units API being defined in JSR-275. Both groups should decide together where basic time duration units (nanosecond, millisecond, second, minute, hour, etc. - see http://en.wikipedia.org/wiki/Category:Units_of_time ) should be defined. There is no need for a both a javax.time.Second and a javax.measure.unit.NonSI.Second class to spring up at the same time in JSE7. Somebody from the expert JSR-310 group should be on the expert group of JRS-275 and visa versa. I'm sure both groups have some similar goals for time and dates and their calculations. And any functionality designed in JRS-275 could simplify work in JSR-310. For example, if JRS-275 is based on JScience and has something like http://jscience.org/api/javax/measure/unit/NonSI.html for units and http://jscience.org/api/org/jscience/mathematics/number/Rational.html for fractions, then some of the proposed unit classes and the Fraction class (https://jsr-310.dev.java.net/nonav/generics/javax/math/Fraction.html) might be unneeded in this project.

-- Main.pdjohe - 09 Sep 2007


Comments

[These comments refer to the closed Generics branch, rather than the active Trunk] - most of these points are addressed there - scolebourne]

* I would have to concur on the integration with the Units package in JSR-275. Lots of possibility for Duration integration. The API as it stands today duplicates a lot of work. And the Units API seems to be better in most cases least of which is its interoperability with other units.

* This API seems really error prone at this point and very inaccurate. Not sure how this is any better than the existing system except for the immutable aspect. For example getMonthOfYear says nothing of whether it will return 0 for Jan or 1?? I assume one but come on. Are we going to have to experiment again like we did with Calendar?? Same is true of getDayOfWeek and getDayOfYear.. Seems little different from Calendar.

* TimeZone seems really weak? Seems it is going to experience all the growing pains of the previous implementation. Why not just use the previous implementation?

* Without the ability to specify TimeZone most of this API seems like it would give you JUNK dates. Is accuracy not part of this spec? Also I am going to assume this either uses the system default Calendar or is going to be extended to support other calendars? Seems way to US centric. Again something that would make it highly innaccurate.

* I see nothing in this API relating to formatting and parsing. Not even so much as a toString() method anywhere. What exactly is this going to be used for?

* Seems vastly over complicated for basically giving you nothing except for moving the basic methods from calendar into new classes.

* All the object construction used along the path of working with these objects is likely to make it perform like a dog. Again what does this give us?

Not trying to be overly critical (I would like to sound more positive) but I see ZERO benefit of this API at this point. Why would you clutter up the JDK with something this inaccurate, unperformant, illogical, and useless?

Now I am talking about the Generics version. Haven't looked at the other API just yet..

-- Main.floersh - 27 Dec 2007


Dates without time and Time intervals Composite

I wish I could retrieve an OffsetDateTime? by calculating the span of a Duration trough a CompositeDateAndTimeInterval?. The composite could behave as this:

    CompositeTimeInterval working_hours = EnhancedTimeInterval(Mon tru fri 8:00 to 20:00)
    TimeInterval lunchbreak = 12:00 to 12:45
    CompositeDateWithoutTime belgiumBankHolidays2008 = 1 Jan 2008, 23 Mar 2008, 24 Mar 2008, 1 May 2008, 11 May 2008, 12 May 2008, 21 Jul 2008, 15 Aug 2008, 1 Nov 2008, 11 Nov 2008, 25 Dec 2008
    CompositeDateWithoutTime specialOpeningDays = Sun 20 Feb (launch of our new super awaited product), Sun 21 Dec (shopping day before Xmas)
    CompositeTimeInterval working_hours_2008 = new CompositeTimeInterval()
    working_hours_2008.include(working_hours)
    working_hours_2008.exclude(lunchbreak)
    working_hours_2008.exclude(belgiumBankHolidays2008)
    working_hours_2008.include(specialOpeningDays)
    When 
      a customer ticket is opened for more than two hours during working_hours_2008
      and state is urgent
    then
      send a reminder to the support team
    
    When 
      a customer ticket is opened for more than five hours during working_hours_2008
      and state is urgent
    then
      escalate ticket

    When 
      a customer ticket is opened for more than 100 hours during working_hours_2008
    then
      report it to the boss

    Duration job_duration = 100h
    Instant now = now()
    Instant planned_job_end = CompositeTimeInterval.span(now, job_duration, agenda_2008)

It would require to enhance Time intervals: Mon tru fri 8:00 to 20:00 (or 8:00 p.m. to 8 a.m.) Also required: "Every first tuesday of the month" calculation method.

Suggestions for a better name are welcome: Date and Time intervals aggregates? Agenda? Complex Time intervals? Time Intervals sets?

-- Main.rusinsky - 27 Dec 2007


DayOfWeek?.dayOfWeek(ReadableDate? dateProvider) implementation

The current code for dayOfWeek(ReadableDate? dateProvider) appears to be incomplete. I'd suggest using an algorithm called Zeller's Congruence (http://en.wikipedia.org/wiki/Zeller's_congruence).

An example implementation:

    private int dayOfWeek(int day, int month, int year) {
        day += ((month < 3) ? year-- : (year - 2));
        return ((((23 * month) / 9) + day + 4 + (year / 4)) - (year / 100) + (year / 400)) % 7;
    }

-- chris_miller - 6 May 2008


Please simplify the API

Currently the date time API of Java has 4 main classes: Date, TimeZone, Calendar, DateFormat. There are some classes that are not usually needed by developers: GregorianCalendar, SimpleTimeZone, SimpleDateFormat.

The current JSR 310 has a bit less than 100 types (classes and interfaces). I would have expected 10 types at most. How I suggest to simplify the API: replace classes such as 'Year' with methods (setYear, getYear). Remove all convenience methods such as getYearOfCentury(). Remove all exception classes and use existing classes such as IllegalArgumentException.

-- Main.thomasmueller2 - 02 Jun 2008

To thomasmueller2: I strongly disagree on your comment to "simplify" the API. Convenience methods and strong typing (like class "Year") make the API easier to understand and use for a human programmer. They reduce the amount of mental mapping you need to do in order to use the API. While a "bigger" API is more work for implementors of that API, it is less work for users if it is well thought out, and users are what matter in API design. For example, Joda Time is a lot easier to use than java.util.Calendar, although Joda Time has many times more classes and methods. The "complexity" of an API cannot be directly calculated from the amount of classes and methods.

-- Main.vpeurala - 15 Oct 2008

Period and date calculations

How can easily create a new Period instance as a result of two dates subtraction? Such a calculation could consider DST changes, etc. Don't you think that some kind of LocalDatesBuilder? would be helpful?

-- Main.leszekw - 04 Jun 2008

Testability considerations

Please make it possible to substitute a "test double" for the system clock. In the current API, one needs to abstract away System#currentTimeMillis() and Date/Calendar creation in order to get control over the system clock in automated tests. Furthermore, a system-level configuration like a JVM parameter won't do the trick - one typically needs a different kind of fake clock for different tests so the underlying "time source" needs to be substitutable at runtime.

So far I've done it a bit like this:

public interface TimeSource {
   long getTime();
}

public class Clock {
   private static TimeSource timesource = new DefaultTimeSource();

   public static void setTimeSource(TimeSource newTimeSource) {
      return timesource = newTimeSource;
   }
   
   public static Clock system() {
      return new ClockImpl(timesource);
   }
}

Yes, that public static setter does "clutter" the API "just" for the sake of testability but the ability to make your tests deterministic clock-wise really matters.

-- Main.lkoskela - 14 Oct 2008

+1 Well put lkoskela, we're doing exactly the same.

-- Main.thrantal - 15 Oct 2008

+1 Well put lkoskela and thrantal. Testability is important. It would be good if there was a similar way to set system clock for tests as there is in Joda Time (DateTimeUtils.setCurrentMillisFixed(), DateTimeUtils.setCurrentMillisSystem() and DateTimeUtils.setCurrentMillisOffset()).

-- Main.vpeurala - 15 Oct 2008

Add Support for the Ethiopian Calendar

Please add support for the Ethiopian Calendar. 90 million people in Ethiopia and Eritrea use it as their official and working calendar. It's NOT a nice-to-have feature, it's a must. See http://en.wikipedia.org/wiki/Ethiopian_calendar and http://ethiopic.org/Calendars/

Libraries like ICU and joda-time already support it, there's no reason why JSR 310 can't.

-- Main.dtaye - 20 Jun 2009

----- Revision r35 - 21 Jun 2009 - 00:36:30 - Main.dtaye