Java毎日1題10


ますます多くの人が私のJava毎日一題シリーズに参加しているのを見て、とても楽しかったです:)
皆さんの支持に感謝して、みんながもっと良い解題方法を提供することを望んで、共に進歩します!
今日から、一連の時間に関するJavaの小さな問題が発売され、時間処理はJavaの基礎の一つのポイントです.そして1.4以降、deprecatedにはよく使われる方法がたくさん落ちています.だから、もう一度勉強する価値があると思います.さあ、くだらないことは言わないで、始めましょう
年月を入力すると、今月の最終日、例えば入力:2006年5月に5月の最終日、「31日」を出力します.
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();
		}
	}

}