java 求一个输入年月,该月份的最大天数

如 输入 201206 最后一天就是 30
201207 我就要得到 31

第1个回答  2012-07-13
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMM");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
Calendar cal = Calendar.getInstance();
Date d = sdf1.parse("201202");
cal.setTimeInMillis(d.getTime());
cal.add(cal.MONTH, 1);
cal.add(cal.DATE, -1);
System.out.println(sdf2.format(cal.getTime()).substring(6, 8));

另外一种比较简单
SimpleDateFormat sdf0 = new SimpleDateFormat("yyyyMM");
Date dd = sdf0.parse("201206");
c.setTime(dd);
int cc=c.getActualMaximum(Calendar.DAY_OF_MONTH);本回答被提问者采纳
第2个回答  2012-07-11
//获取指定年月的月份的天数
//参数为字符串, 格式 yyyyMM
private int getMonthDays(String str){
int month = Integer.parseInt(str.substring(4));
switch(month){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 4:
case 6:
case 9:
case 11:
return 30;
case 2:
int year = Integer.parseInt(str.substring(0,3));
if((year%4==0 && year%100!=0) || year%400==0)
return 29;
else
return 28;
}
return 0;
}
第3个回答  2012-07-11
如 输入 201206 最后一天就是 30 201207 我就要得到 31
第4个回答  2012-07-11
先判断是不是2月,在判断 135781012就可以了2月要特殊处理
相似回答