如何在java中使用FastDateFormat来查找当前日期是否在给定日期之间?

时间:2015-11-17 10:27:25

标签: java date

我有一个接受2个日期字符串的方法 - startDateString和endDateString。 它是“yyyy-MM-dd HH:mm:ss.S”格式。 现在我必须在今天(当前日期)返回true,否则返回false。

我必须使用FastDateFormat。

请建议。

public boolean effective(String startDateString, String endDateString) {
...
}

1 个答案:

答案 0 :(得分:5)

FastDateFormat的文档是in the Apache Commons website。当你被要求使用特定的课时,这总是第一个转向的地方。

现在,FastDateFormat有一个protected构造函数。您应该使用许多getInstance静态工厂方法中的一种来提供FastDateFormat

,而不是使用其构造函数。
FastDateFormat fullDateFormat = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss.S");

现在,如果您要使用这种格式,那么在类中将其定义为常量是有意义的:

public static final FastDateFormat FULL_DATE_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss.S");

现在,您可以使用它来解析两个日期字符串:

try {
    long startTime = FULL_DATE_FORMAT.parse( startDateString ).getTime();
    long endTime = FULL_DATE_FORMAT.parse( endDateString ).getTime();

    long currentTime = System.currentTimeMillis();

    return currentTime >= startTime && currentTime < endTime;
} catch ( ParseException e ) {
    throw new IllegalArgumentException( "Improperly formatted date", e );
}

现在,它会告诉您当前时间是否在这些字符串所代表的两个时间戳之间。

正如我在评论中提到的,在这种特定的格式中,因为它将日期从最重要的字段排列到固定大小字段中的最不重要字段,所以实际上可以比较字符串。请注意,这并非完全正确 - 除非您在结尾使用格式.SSS而不是.S,否则毫秒字段将会出现问题。如果毫秒部分在您的上下文中不重要,那么您将这样做:

String currDate = FULL_DATE_FORMAT.format( new Date() );
return currDate.compareTo( startDateString ) >= 0
       && currDate.compareTo( endDateString ) < 0;

注意:如果您使用的是Java 8,建议使用其java.time包来表示日期和时间,而不是DateDateFormatCalendar系列类。它的格式化程序是不可变的和线程安全的,所以你不需要FastDateFormat类。

相关问题