java输出每月有多少天

package test;

public class DateTest {

public static void main(String[] args) {
System.out.println(DateTest.getDay(2000, 2));
}

public static int getDay(int year,int month){
int day = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
day = 31;
break;
case 4:
case 6:
case 9:
case 11:
day = 30;
break;
default:
if((year%4==0&&year%100!=0)||year%400==0)
day = 29;
else
day = 28;
break;
}
return day;
}

}



更优的代码如下:[url]http://zhidao.baidu.com/question/41887636.html[/url]

package cn.com.songjy.date;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class CalendarTester {
private static SimpleDateFormat format = new SimpleDateFormat("yyyyMM");

/** * @param args */
public static void main(String[] args) {
String source = "200702";
try {
Date date = format.parse(source);
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
System.out
.println(calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
} catch (ParseException e) {
e.printStackTrace();
}
}
}


备忘

/**
* 获取<start>和<end>之间的月数,包括边界
*
* @method getMonths
* @param start
* @param end
* @return
* @throws ParseException
* @since v1.0
*/
public static Set<String> getMonths(Date start, Date end)
throws ParseException {

Set<String> set = new TreeSet<>();

if (null == start || null == end)
return set;

if (start.compareTo(end) > 0) {
Date date = start;
start = end;
end = date;
}

String s_start = DateFormatUtils.format(start, "yyyy-MM");
String s_end = DateFormatUtils.format(end, "yyyy-MM");

set.add(s_end);

if (s_start.equals(s_end))
return set;

Calendar c_start = Calendar.getInstance();
c_start.setTime(start);

Calendar c_end = Calendar.getInstance();
c_end.setTime(end);

while (true) {

c_start.add(Calendar.DAY_OF_MONTH, 1);

Date date = c_start.getTime();

String s_date = DateFormatUtils.format(date, "yyyy-MM");

set.add(s_date);

if (s_end.equals(s_date))
break;

}

set.add(s_start);
set.add(s_end);

return set;

}


	public void demo() throws IOException, ParseException {

String[] allMonths = { "2014-01", "2014-02", "2014-03", "2014-04" };

String start = allMonths[0];

for (int i = 0; i < allMonths.length; i++) {

Date d = DateUtils.addMonths(DateUtils.parseDate(start, "yyyy-MM"),
2);

String t = DateFormatUtils.format(d, "yyyy-MM");

int index = ArrayUtils.indexOf(allMonths, t);

if (index >= 0) {

System.out.println("1," + start + "," + t);

d = DateUtils.addMonths(d, 1);

start = DateFormatUtils.format(d, "yyyy-MM");

} else {

if (ArrayUtils.indexOf(allMonths, start) >= 0)
System.out.println("2," + start + "," + allMonths[allMonths.length - 1]);
break;
}

}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值