参见英文答案 > How to get the first date and last date of the previous month? (Java) 7个
我想获得给定月份和年份的第一个日期和最后日期.我使用以下代码以yyyyMMdd格式获取最后一个日期.但是无法获得这种格式.然后我想以相同的格式开始日期.我还在努力.任何人都可以帮我修复下面的代码.
public static java.util.Date calculateMonthEndDate(int month, int year) {
int[] daysInAMonth = { 29, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int day = daysInAMonth[month];
boolean isLeapYear = new GregorianCalendar().isLeapYear(year);
if (isLeapYear && month == 2) {
day++;
}
GregorianCalendar gc = new GregorianCalendar(year, month - 1, day);
java.util.Date monthEndDate = new java.util.Date(gc.getTime().getTime());
return monthEndDate;
}
public static void main(String[] args) {
int month = 3;
int year = 2076;
final java.util.Date calculatedDate = calculateMonthEndDate(month, year);
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
format.format(calculatedDate);
System.out.println("Calculated month end date : " + calculatedDate);
}
解决方法:
获取开始日期
GregorianCalendar gc = new GregorianCalendar(year, month-1, 1);
java.util.Date monthEndDate = new java.util.Date(gc.getTime().getTime());
System.out.println(monthEndDate);
(注意:在开始日期当天= 1)
为格式化
SimpleDateFormat format = new SimpleDateFormat(/add your format here);
System.out.println("Calculated month end date : " + format.format(calculatedDate));
标签:java,date,calendar
来源: https://codeday.me/bug/20191004/1854170.html