Java每日一题10

看到有越来越多的人来参与到我的Java每日一题系列,非常开心:)
感谢大家的支持,希望大家多多提供更好的解题方法,共同进步!
从今天开始,先推出一系列时间相关的Java小问题,时间处理是Java基础中的一个要点。而且1.4以后,被deprecated掉了很多常用的方法。所以我认为值得重新学习下。好了,不废话了,开始->

[color=blue]当输入一个年月份的时候,输出这个月份的最后一天,比如输入: 2006年5月 就输出5月份的最后一个日,“31日”。 [/color]

package test26;

public class LastDay {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
String s = new LastDay().getDate("200805");
System.out.println(s);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public String getDate(String yearmonth) throws Exception {
int year = 0;
int month = 0;
String enddate = "";
try {
year = (new Integer(yearmonth.substring(0, 4))).intValue();
month = (new Integer(yearmonth.substring(4, 6))).intValue();
if (month == 1 || month == 3 || month == 5 || month == 7
|| month == 8 || month == 10 || month == 12) {
enddate = "31";
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
enddate = "30";
} else if (month == 2
&& ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)) {
enddate = "29";
} else {
enddate = "28";
}
} catch (Exception ex) {
ex.printStackTrace();
}
return enddate;
}

}


或者
package test26;

import java.util.Calendar;

public class ThefLastDay {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
new ThefLastDay().getDate("200902");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public void getDate(String yearmonth) throws Exception {
int year = 0;
int month = 0;
try {
year = (new Integer(yearmonth.substring(0, 4))).intValue();
month = (new Integer(yearmonth.substring(4, 6))).intValue();
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, 1);
calendar.set(Calendar.DATE, (calendar.get(Calendar.DATE) - 1));
System.out.println(calendar.get(Calendar.DAY_OF_MONTH));
} catch (Exception ex) {
ex.printStackTrace();
}
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值