answer by Jim Garrison 是正确的,但很简短。我决定尝试一个实现。在 Mac 上使用 Joda-Time 2.3 和 Java 7。
如果你经常使用这种“联合”方法,也许你应该考虑创建一个Interval 的子类来添加一个方法,在该方法中你传递一个(第二个)间隔来与第一个进行比较正在调用谁的方法。
对于偶尔的使用,在某个实用程序类上使用静态方法就足够了。这就是我在这里写的,一个传递一对间隔的静态方法。返回一个新的间隔。
我的示例代码没有使用多行if 语句,而是使用?: ternary operator 将拉动第一或第二DateTime 的决定折叠到一行。
静态方法……
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
static Interval union( Interval firstInterval, Interval secondInterval )
{
// Purpose: Produce a new Interval instance from the outer limits of any pair of Intervals.
// Take the earliest of both starting date-times.
DateTime start = firstInterval.getStart().isBefore( secondInterval.getStart() ) ? firstInterval.getStart() : secondInterval.getStart();
// Take the latest of both ending date-times.
DateTime end = firstInterval.getEnd().isAfter( secondInterval.getEnd() ) ? firstInterval.getEnd() : secondInterval.getEnd();
// Instantiate a new Interval from the pair of DateTime instances.
Interval unionInterval = new Interval( start, end );
return unionInterval;
}
示例用法……
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
// Note the various time zones.
Interval i1 = new Interval( new DateTime( 2013, 1, 1, 0, 0, 0, DateTimeZone.forID( "America/Montreal" ) ), new DateTime( 2013, 1, 5, 0, 0, 0, DateTimeZone.forID( "America/Montreal" ) ) );
Interval i2 = new Interval( new DateTime( 2013, 1, 10, 0, 0, 0, DateTimeZone.forID( "Europe/Paris" ) ), new DateTime( 2013, 1, 15, 0, 0, 0, DateTimeZone.forID( "Europe/Paris" ) ) );
Interval i3 = TimeExample.union( i1, i2 );
转储到控制台...
System.out.println("i1: " + i1 );
System.out.println("i2: " + i2 );
// Note that Joda-Time adjusts the ending DateTime's time zone to match the starting one.
System.out.println("i3: " + i3 );
运行时……
i1: 2013-01-01T00:00:00.000-05:00/2013-01-04T18:00:00.000-05:00
i2: 2013-01-10T00:00:00.000+01:00/2013-01-15T00:00:00.000+01:00
i3: 2013-01-01T00:00:00.000-05:00/2013-01-14T18:00:00.000-05:00