這個問題在這里已經有了答案: 在 Java 中添加 30 天到日期 (7 個回答) 如何在 Java 中將日期增加一天? (32 個回答) 在 Java 中為日期添加天數 [重復] (6 個回答) 如何在 Java 中檢查日期是否大于另一個日期?[重復] (4 個回答) 12 小時前關閉。
我的當前日期格式類似于 20211231,我想在該日期后添加 150 天。在那之后,如果時間還不到 150 天,我如何檢查它或通過它
我已經嘗試使用此代碼將 150 天添加到當前日期,但失敗了
Calendar c= Calendar.getInstance();
c.add(Calendar.DATE, 150);
Date d = c.getTime ();
idk 如果那不再起作用了,或者自從我讀了一個 9 年零 5 個月前問和回答的問題https://stackoverflow.com/a/11727986/17562398
這是我目前的日期選擇器
SimpleDateFormat cdate = new SimpleDateFormat ("yyyyMMdd", Locale.getDefault ( ));
String currentDate = cdate.format (new Date ( ));
uj5u.com熱心網友回復:
使用包中的現代 Java 時間 API java.time.*。
可以使用該java.time.format.DateTimeFormatter.ofPattern(String, Locale)方法以所需格式決議或格式化(用于顯示)日期。這是DateTimeFormatter類的檔案
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyyMMdd", locale);
如果您正在決議用戶輸入的日期,請不要忘記捕獲決議例外。
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
//...
// The desired locale, maybe the target user selected language/region locale?
// For now just using the default locale here
Locale locale = Locale.getDefault();
String someInputDate = "20220529";
try {
// using the DateTimeFormatter to parse the date with a desired pattern
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyyMMdd", locale);
LocalDate inputDate = LocalDate.parse(someInputDate, dateFormatter);
// 150 days from now
int daysFromNow = 150;
LocalDate targetDate = LocalDate.now().plusDays(daysFromNow);
android.util.Log.d(
"Dates", String.format("The date %d days from now is %s", daysFromNow, targetDate.format(dateFormatter))
);
if (inputDate.isAfter(targetDate)) {
// the input date is past 150 day from now
android.util.Log.d(
"Dates", String.format("%s at least %d days from now", inputDate.format(dateFormatter), daysFromNow)
);
} else {
// the input date is NOT past 150 day from now
android.util.Log.d(
"Dates", String.format("%s is less than %d days from now", inputDate.format(dateFormatter), daysFromNow)
);
}
} catch (DateTimeParseException e) {
// The input is a date in a different format or is malformed/invalid
}
日志輸出
Dates The date 150 days from now is 20220530
Dates 20220529 is less than 150 days from now
uj5u.com熱心網友回復:
這是我使用當前日期(今天)檢查 150 天的邏輯
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
String sDate="20211231";
Date cuDate=dateFormat.parse(sDate);
Date currentDate = new Date();
Calendar calendarObj = Calendar.getInstance();
calendarObj.setTime(cuDate);
calendarObj.add(Calendar.MONTH, 5); // since this is 150 days (i think it's 30 days * 5 )
Date newDateAfter5months = calendarObj.getTime();
System.out.println("newDateAfter5months=" dateFormat.format(newDateAfter5months));
if(newDateAfter5months.compareTo(currentDate) > 0) {
System.out.println("newDateAfter5months occurs after currentDate");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/399672.html
上一篇:ngFor不要在來自谷歌地點自動完成的place_changed事件之后立即顯示所有專案
下一篇:位元組陣列到字串的轉換
