看到有越来越多的人来参与到我的Java每日一题系列,非常开心:)
感谢大家的支持,希望大家多多提供更好的解题方法,共同进步!
从今天开始,先推出一系列时间相关的Java小问题,时间处理是Java基础中的一个要点。而且1.4以后,被deprecated掉了很多常用的方法。所以我认为值得重新学习下。好了,不废话了,开始->
[color=blue]当输入一个年月份的时候,输出这个月份的最后一天,比如输入: 2006年5月 就输出5月份的最后一个日,“31日”。 [/color]
或者
感谢大家的支持,希望大家多多提供更好的解题方法,共同进步!
从今天开始,先推出一系列时间相关的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();
}
}
}