要检查日期是否在指定日期之后?

时间:2013-02-15 10:19:24

标签: java date

我正在尝试对日期进行验证,该日期应仅包含当前和未来日期,如果日期是旧日期则应显示

  

日期早于当天

我想也允许当前日期。现在正在给gievnDate作为当天,它总是显示

  

日期早于当天

但我希望输出为

  

日期是未来日    对于givenDate而言,就像今天一样。

以下是我一直在尝试的代码:

    Date current = new Date();
    String myFormatString = "dd/MM/yy";
    SimpleDateFormat df = new SimpleDateFormat(myFormatString);
    Date givenDate = df.parse("15/02/13");
    Long l = givenDate.getTime();
    //create date object
    Date next = new Date(l);
    //compare both dates
    if(next.after(current) || (next.equals(current))){
        System.out.println("The date is future day");
    } else {

        System.out.println("The date is older than current day");
    }

在这里,当我在15/02/13查看时,它显示为比当前日期更早。我的方法错了吗?还是有更好的方法?

5 个答案:

答案 0 :(得分:8)

if(next.after(current) && (next.equals(current)))始终为false,因为next不能严格地current并且同时等于current。{/ p>

你可能意味着:

带有OR的

if(next.after(current) || (next.equals(current)))

答案 1 :(得分:3)

除了assylias指出的逻辑错误:

您的示例中没有指定givenDate为“15/02/13 00:00:00.000”的时间。现在,如果您将该给定日期与同一天的任何实时时间戳(即“现在”)进行比较,那么givenDate几乎总是“较旧”,然后是“现在”。

givenDate设置为当天的最后一毫秒,您将不需要“等于”测试。

答案 2 :(得分:3)

TL;博士

LocalDate                                      // Represents a date-only, without time-of-day and without time zone.
.parse( 
    "15/02/13" , 
    DateTimeFormatter.ofPattern( "dd/MM/uu" )  // Specify a format to match you're input.
)                                              // Returns a `LocalDate` object.
.isBefore(                                     // Compare one `LocalDate` to another.
    LocalDate.now(                             // Capture the current date…
        ZoneId.of( "America/Montreal" )        // …as seen through the wall-clock time used by the people of a particular region (a time zone).
    )                                          // Returns a `LocalDate` object.
)                                              // Returns a boolean.

详细

其他答案对于布尔逻辑中的错误是正确的。

此外,您正在使用麻烦的旧日期时间类,现在是旧的,取而代之的是java.time类。

isBefore&提到的布尔逻辑更容易isAfter类上的java.time.LocalDate方法。

LocalDate

LocalDate类表示没有时间且没有时区的仅限日期的值。

时区对于确定日期至关重要。对于任何给定的时刻,日期在全球范围内因地区而异。例如,在Paris France午夜后的几分钟是新的一天,而Montréal Québec中仍然是“昨天”。

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );

DateTimeFormatter

要将输入字符串解析为日期时间值,请使用DateTimeFormatter类。

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uu" );
String input = "15/02/13";
LocalDate ld = LocalDate.parse( input , f );

比较

要比较LocalDate个对象,您可以调用compareToequalsisAfterisBeforeisEqual等方法。

String message = "ERROR - Message not set. Error # f633d13d-fbbc-49a7-9ee8-bcd1cfa99183." ;
if( ld.isBefore( today ) ) {  // Before today.
   message = "The date: " + ld + " is in the past, before today: " + today );
} else if( ld.isEqual( today ) ) {  // On today.
   message = "The date: " + ld + " is today: " + today );
} else if( ld.isAfter( today ) ) {  // After today.
   message = "The date: " + ld + " is in the future, later than today: " + today );
} else {  // Double-check.
   message = "ERROR – Unexpectedly reached Case Else. Error # c4d56437-ddc3-4ac8-aaf0-e0b35fb52bed." ) ;
}

格式

顺便说一句,缺少世纪的输入字符串的格式是不明智的。使用年份的两个数字会使日期更难阅读,产生更多的歧义,并使解析更加困难,因为各种软件在违约世纪时表现不同。我们现在可以在现代计算存储器和存储器中提供两个额外的数字。

将日期时间值序列化为文本时,请坚持使用实用且流行的ISO 8601标准格式。仅限日期,即YYYY-MM-DD,例如2016-10-22

关于java.time

java.time框架内置于Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如java.util.DateCalendar和& SimpleDateFormat

现在位于Joda-Timemaintenance mode项目建议迁移到java.time。

要了解详情,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。规范是JSR 310

从哪里获取java.time类?

ThreeTen-Extra项目使用其他类扩展java.time。该项目是未来可能添加到java.time的试验场。您可以在此处找到一些有用的课程,例如IntervalYearWeekYearQuartermore

答案 3 :(得分:2)

此代码中至少有一个错误,但我看不出它会如何引发异常。声明:

if(next.after(current) && (next.equals(current))){

永远不会评估为true,因为可能next.after(current)next.equals(current)并非同时为真。

你可能想写:

if(next.after(current) || (next.equals(current))){

此外,至少包含错误的具体细节通常是一个好主意:抛出异常的确切行(如果这确实是你的意思),以及确切的输出是什么(即使输出是一个例外)给出了什么输入?

答案 4 :(得分:-1)

尽管这是一个老问题 我想分享一个简单的解决方案 您可以检查当前日期是否不在下一个日期之前。 因为如果它不等于当前日期或当前日期之后。这就是你要找的东西。 所以你不需要“OR等于”检查。

if(!current.isBefore(next)){
     System.out.println("The date is future day");
}else{
     System.out.println("The date is older than current day");
}

或者您甚至可以使用:

if(next.getTime() >= current.getTime())