簡體   English   中英

如何在Java中檢查用戶輸入的日期距離當前日期大於32天

[英]How to check user entered date is greater than 32 days from current date in java

我想根據條件驗證用戶的日期輸入。 條件是用戶輸入的新日期應大於32天。 該怎么做? 我嘗試了以下方法,但無法正常工作。

final Date getuserDate = validate.date();
logger.debug("UserDate is" + getuserDate);
DateTime currentExpdelDate = new DateTime(getuserDate);
DateTime currentDate = new DateTime();

DateTime dtPlus = currentDate.plusDays(32);
long millisec = dtPlus.getMillis() - currentExpdelDate.getMillis();
if (millisec > 0) {
    long diffDays = millisec / (24 * 60 * 60 * 1000);
    if (diffDays < 32) {

        System.out.println("Date should be greater than 32 days")
    }
}

通用類型DateTime不適合僅日期的任務。 因此,您應該在Joda-Time-library中選擇LocalDate類型。

然后,您可以使用此構造函數 請注意,您需要指定時區,因為當前日期不是世界上同一時間的同一日期。

java.util.Date input = ...;
DateTimeZone zone = DateTimeZone.forID(...);

LocalDate userDate = new LocalDate(input, zone);
boolean exclude = new LocalDate(zone).plusDays(32).isAfter(userDate);

if (exclude) {
  System.out.println("Date should be greater than 32 days in the future.");
}

如果您已經在使用Java 8 ,則可以使用plusDays()isBefore()方法使用其新的LocalDate類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM