开发者

Joda-Time: DateTime, DateMidnight and LocalDate usage

Joda-Time library includes different datetime classes

DateTime - Immutable replacement for JDK Calendar

DateMidnight - Immutable class representing a date where the time is forced to midnight

LocalDateTime - Immutable class representing a local date and time (no time zone)

I'm wondering how are you using these classes in your Layered Applications.

I see advantages in having almost all the Interfaces using LocalDateTime (at the Service Layer at least) so that my Application doesn't have to manage Timezones and can safely assume Times always in UTC. My app could then use DateTime to manage Tim开发者_开发百科ezones at the very beginning of the Execution's Flow.

I'm also wondering in which scenario can DateMidnight be useful.


I see advantages in having almost all the Interfaces using LocalDateTime (at the Service Layer at least) so that my Application doesn't have to manage Timezones and can safely assume Times always in UTC.

I'm not sure I understand your line of thinking here. LocalDateTime and DateTime represent two quite different concepts. It's not the case that a LocalDateTime has some implicit UTC timezone: it actually has no timezone (internally it may be represented as a DateTime with UTC timezone, but it's just a implementation detail, it does not matter to the programmer who uses it).

You can see in the API docs that, while a DateTime is a "Instant" (a point in the world time line, a physical concept), a LocalDateTime is NOT such a thing. The LocalDateTime is actually a Partial, (a "civil" concept), in a different class hierarchy. The classes names might -unfortunately- make you think that LocalDateTime is some specialization of DateTime: well, it isn't.

A LocalDateTime should be regarded as a pair {Date (Y/M/D) ; Time (hh:mm:ss.msec)}, a bunch of numbers which corresponds to the "civil" standard representation of time-related data. If we are given a LocalDateTime, we cannot convert it directly to a DateTime, we need to specify a timezone; and that conversion takes we to another kind of entity. (An analogy: Strings and byte streams in Java: to convert between them you must specify a charset encoding, because they are conceptually different things)

When to use one or the other in the application... it's sometimes arguable, but frequently is clear enough, once the Jodatime concepts are understood. And IMO is not much related to "layers", perhaps more to use cases or scenarios.

A non-trivial -borderline- example: You work at Google, programming the Calendar. You must let the user manage (add, see, modify) an event which includes a date-time (lets ignore recurrent events), say "I have an appointement with my doctor on 2019-July-3 at 10:00 am". What is the time-date entity to use in the software layer (for this usecase)? I'd say: a LocalDateTime. Because the user is not really dealing with a physical point in time, but with a civil time: the date and time that displays the clock in his wrist or in his home. He does not even think of timezones (lets ignore the special case of a user who is traveling around the world...) Then, in the bussiness and presentation layer, a LocalDateTime seems the right entity.

But suppose that you must also code a different scenario: a reminder. When the Google internal scheduler detects that the event stored by the user is N minutes in the future from now, it must send him a reminder. Here, "N minutes from now" is a totally "physical" concept of time, so here the "business layer" would deal with a DateTime. There are several alternatives, for example: the event was stored in the DB as a LocalDateTime (ie. just time and date without timezone - one frequently uses a UTC timestamp to represent that, but this an implementation detail). In this scenario (only in this) we must load it as a DateTime, we convert it using a Timezone, probably from the user's profile.


The Answer by leonbloy is correct and vitally important. I am merely translating to the java.time classes that replace the Joda-Time project.

java.time

Specific moment

For a specific moment on the timeline:

  • Always in UTC is represented by Instant.
  • Assigned an offset-from-UTC is represented by OffsetDateTime.
  • Assign a full time zone rather than mere offset is represented by ZonedDateTime.

These all replace the Instant & DateTime class in Joda-Time. These java.time classes all have a resolution of nanoseconds versus the milliseconds used by Joda-Time.

Midnight versus Start-of-day

For midnight, the Joda-Time project concluded “midnight” is a vague and unproductive concept. The midnight-related classes and midnights were all deprecated in later versions of Joda-Time, replaced with the practical concept of “first moment of the day”.

The java.time classes took the same lesson, using a "first moment of the day" approach. Look for atStartOfDay methods on java.time classes such as LocalDate.

Never assume a day starts at 00:00. Anomalies such as Daylight Saving Time (DST) mean the day may start at other times such as 01:00.

ZonedDateTime zdt = 
    LocalDate.of( 2017 , Month.MARCH , 12 )                    // Instantiate a date-only value without time zone.
             .atStartOfDay( ZoneId.of( "America/Havana" ) ) ;  // Cuba jumps from 00:00 to 01:00 on Spring DST cut-over.

For example, see how Cuba starts the day at 1 AM on their Spring DST cut-over.

zdt: 2017-03-12T01:00-04:00[America/Havana]

Unzoned

For representing the vague idea of possible moments over a range of about 26-27 hours but not an actual moment on the timeline, use LocalDateTime. This class purposely lacks any offset-from-UTC or time zone.

LocalDateTime ldt = LocalDateTime.of( 2017 , Month.JANUARY , 23 , 1 , 2 , 3 , 0 ) ;

If your business context implies a specific time zone, you can apply it to get a ZonedDateTime.

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;  // Determine a specific point on timeline by providing the context of a time zone.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
    • See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜