我有一個下面的函式,它有一個輸入日期,它將以格式回傳下個月的第一個和最后一個日期。MM/dd/yyyy
String string = "01/01/2022";
DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date dt = sdf .parse(string);
Calendar c = Calendar.getInstance();
c.setTime(dt);
c.add(Calendar.MONTH, 1);
String firstDate = sdf.format(c.getTime());
System.out.println("FirstDate:" firstDate);
c.add(Calendar.MONTH, 1);
c.add(Calendar.DAY_OF_MONTH, -1);
String lastDate = sdf.format(c.getTime());
System.out.println("LastDate:" lastDate);
以上將為我提供如下輸出
FirstDate:02/01/2022
LastDate:02/28/2022
如果輸入是上個月的第一天,這很好用,我想要實作的是獲取下一個的 FirstDate 和 LastDate,month即使輸入的日期不是該月的第一個日期,例如01/31/2022給出我下面的輸出
FirstDate:02/28/2022
LastDate:03/27/2022
但我仍然希望它給我第一個
FirstDate:02/01/2022
LastDate:02/28/2022
uj5u.com熱心網友回復:
不要使用 Date,因為它已經過時且有問題。使用java.time包中的LocalDate和其他類。
- 以下首先采用現有日期,添加
1到月份。如果需要,這也將導致年份增加。 - 然后
dayOfMonth是1一個月的最后一天或最后一天。閏年被自動考慮。
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM/dd/yyyy");
LocalDate date = LocalDate.parse("12/22/2020", dtf);
date = date.plusMonths(1);
LocalDate endDate = date.withDayOfMonth(date.lengthOfMonth());
LocalDate startDate = date.withDayOfMonth(1);
System.out.println("FirstDate: " startDate.format(dtf));
System.out.println("LastDate: " endDate.format(dtf));
印刷
FirstDate: 01/01/2021
LastDate: 01/31/2021
uj5u.com熱心網友回復:
你可以在 Java 8 中更輕松地做到這一點。使用 a java.time.YearMonth,使用它的方法獲取當前的now()并派生它的第一個和最后一個LocalDate:
public static void main(String[] args) {
// get the current month
YearMonth currentMonth = YearMonth.now();
// get the date with day of month = 1 using the current month
LocalDate firstOfMonth = currentMonth.atDay(1);
// then get its last date (no number required here)
LocalDate lastOfMonth = currentMonth.atEndOfMonth();
// prepare a formatter for your desired output (default: uuuu-MM-dd)
DateTimeFormatter customDtf = DateTimeFormatter.ofPattern("MM/dd/uuuu");
// print the month and year without a formatter (just for visualization)
System.out.println("Month: " currentMonth);
// then print both desired dates using the custom formatter
System.out.println("FirstDate: " firstOfMonth.format(customDtf));
System.out.println("LastDate: " lastOfMonth.format(customDtf));
}
這列印
Month: 2022-05
FirstDate: 05/01/2022
LastDate: 05/31/2022
當然,您可以使用任何給定的月份,YearMonth.of(int year, int month)您可以使用它來創建示例值:
YearMonth currentMonth = YearMonth.of(2022, 2);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/479127.html
