更新: Joda-Time 库现在处于维护模式,其主要作者 Stephen Colebourne 继续领导 JSR 310,它定义了Java 8 及更高版本中内置的java.time类。
一个对日期时间具有复杂支持的良好数据库在这里可能会有所帮助。一个这样的数据库是Postgres,具有良好的日期时间数据类型和命令(“函数”)。
Joda-Time框架也可能有所帮助。Interval类及其父类定义了一对开始和停止日期时间之间的时间跨度。它们提供了比较方法,例如:包含、重叠、isBefore、is After。
下面是一些示例代码,可帮助您开始使用 Joda-Time 2.3 和 Java 7。
// © 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.*;
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
List<Interval> workIntervalsFor13Aug2012 = new ArrayList<Interval>( 2 );
DateTime start, stop;
Interval interval;
start = new DateTime( 2012, 8, 13, 8, 0, 0, timeZone );
stop = new DateTime( 2012, 8, 13, 14, 0, 0, timeZone );
interval = new org.joda.time.Interval( start, stop );
workIntervalsFor13Aug2012.add( interval );
start = new DateTime( 2012, 8, 13, 15, 0, 0, timeZone );
stop = new DateTime( 2012, 8, 13, 18, 0, 0, timeZone );
interval = new org.joda.time.Interval( start, stop );
workIntervalsFor13Aug2012.add( interval );
// Check a date-time against those work intervals.
DateTime test09 = new DateTime( 2012, 8, 13, 9, 0, 0, timeZone );
DateTime test21 = new DateTime( 2012, 8, 13, 21, 0, 0, timeZone );
// You should write a "dateTimeIsInWorkingInterval" method that performs this loop.
Boolean hit = false;
for ( Interval nthInterval : workIntervalsFor13Aug2012 ) {
if( nthInterval.contains( test09 )) {
hit = true;
break;
}
}
if( hit ) {
System.out.println( "This date-time: " + test09 + " occurs during a work interval.");
} else {
System.out.println( "This date-time: " + test09 + " occurs outside a work interval.");
}
hit = false;
for ( Interval nthInterval : workIntervalsFor13Aug2012 ) {
if( nthInterval.contains( test21 )) {
hit = true;
break;
}
}
if( hit ) {
System.out.println( "This date-time: " + test21 + " occurs during a work interval.");
} else {
System.out.println( "This date-time: " + test21 + " occurs outside a work interval.");
}
运行时……</p>
This date-time: 2012-08-13T09:00:00.000+02:00 occurs during a work interval.
This date-time: 2012-08-13T21:00:00.000+02:00 occurs outside a work interval.