java获取给定月份和给定年份的第一个日期和最后一个日期
问题描述:
我试图获取给定月份和年份的第一个日期和最后一个日期。我使用以下代码获取格式为yyyyMMdd的最后一个日期。但不能得到这种格式。此外,我想开始日期以相同的格式。我还在做这个。任何人都可以帮助我修复下面的代码。
I am trying to get the first date and the last date of the given month and year. I used the following code to get the last date in the format yyyyMMdd. But couldnot get this format. Also then I want the start date in the same format. I am still working on this. Can anyone help me in fixing the below code.
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);
}
答
开始日期
To get the Start Date
GregorianCalendar gc = new GregorianCalendar(year, month-1, 1);
java.util.Date monthEndDate = new java.util.Date(gc.getTime().getTime());
System.out.println(monthEndDate);
( 注意 格式化的
(Note : in the Start date the day =1)
for the formatted
SimpleDateFormat format = new SimpleDateFormat(/////////add your format here);
System.out.println("Calculated month end date : " + format.format(calculatedDate));