Java 8 java.time Classes – Missing getMillis() Method Explained

javajava8

Java 8 has a whole new library for dates and times in the package java.time which is very welcome thing to anyone who has had to use JodaTime before or hassle with making it's own date processing helper methods. Many classes in this package represent timestamps and have helper methods like getHour() to get hours from timestamp, getMinute() to get minutes from timestamp, getNano() to get nanos from timestamp etc…

I noticed that they don't have a method called getMillis() to get the millis of the time stamp. Instead one would have to call method get(ChronoField.MILLI_OF_SECOND). To me it seems like an inconsistency in the library. Does anyone know why such a method is missing, or as Java 8 is still in development is there a possibility that it will be added later?

https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html

The classes defined here represent the principal date-time concepts, including instants, durations, dates, times, time-zones and periods. They are based on the ISO calendar system, which is the de facto world calendar following the proleptic Gregorian rules. All the classes are immutable and thread-safe.

Each date time instance is composed of fields that are conveniently made available by the APIs. For lower level access to the fields refer to the java.time.temporal package. Each class includes support for printing and parsing all manner of dates and times. Refer to the java.time.format package for customization options…

Example of this kind of class:
https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html

A date-time without a time-zone in the ISO-8601 calendar system, such as 2007-12-03T10:15:30.

LocalDateTime is an immutable date-time object that represents a date-time, often viewed as year-month-day-hour-minute-second. Other date and time fields, such as day-of-year, day-of-week and week-of-year, can also be accessed. Time is represented to nanosecond precision. For example, the value "2nd October 2007 at 13:45.30.123456789" can be stored in a LocalDateTime

Best Answer

JSR-310 is based on nanoseconds, not milliseconds. As such, the minimal set of sensible methods are based on hour, minutes, second and nanosecond. The decision to have a nanosecond base was one of the original decisions of the project, and one that I strongly believe to be correct.

Adding a method for millis would overlap that of nanosecond is a non-obvious way. Users would have to think about whether the nano field was nano-of-second or nano-of-milli for example. Adding a confusing additional method is not desirable, so the method was omitted. As pointed out, the alternative get(MILLI_OF_SECOND) is available.

FWIW, I would oppose adding the getMillis() method in the future.