JAvaアルゴリズム---任意の日の前日を取得



package com.huifudianxia.interview;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
 *  
 * @author yangjianzhou
 *
 */
public class Interview {

	public static void main(String[] args) {
		Interview inter = new Interview();
		System.out.println(inter.method1("13-11-2"));
		System.out.println(inter.method2("2013-11-2"));
	}

	/**
	 *  java API
	 * @param specifiedDay
	 * @return
	 */
	public  String method1(String specifiedDay){
		Calendar c = Calendar.getInstance();
		Date date = null;
		try{
			date = new SimpleDateFormat("yy-MM-dd").parse(specifiedDay);
		}catch (Exception e) {
			e.printStackTrace();
		}
		c.setTime(date);
		int day = c.get(Calendar.DATE);
		c.set(Calendar.DATE, day-1);
		String dayBefore = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
		return dayBefore;
	}

	/**
	 *  java API
	 * @param specifiedDay
	 * @return
	 */
	public String method2(String specifiedDay){
		String beforeDay = "";
		String [] date = specifiedDay.split("-");
		int year = Integer.parseInt(date[0]);
		int month = Integer.parseInt(date[1]);
		int day = Integer.parseInt(date[2]);
		if(day>1){
			beforeDay = year+"-"+month+"-"+(day-1);
		}else{
			if(month>1){
				day = getDays(month-1,year);
				beforeDay = year+"-"+(month-1)+"-"+day;
			}else{
				year = year -1;
				beforeDay = year+"-"+12+"-"+"31";
			}
		}
		return beforeDay;
	}

	public int getDays(int month,int year){
		int days ;
		switch(month){
		case 1 :
		case 3 :
		case 5 :
		case 7 :
		case 8 :
		case 10 :
		case 12 : days =  31;
		break;
		case 4 :
		case 6 :
		case 9 :
		case 11 : days =30;
		break;
		default :{
			if(isLeap(year)){
				days = 29;
			}else{
				days =28;
			}
		}
		}
		return days;
	}
	/**
	 *  
	 * @param year
	 * @return
	 */
	public boolean isLeap(int year){
		if((year%4==0)&&(year%100!=0)){
			return true;
		}else if(year%400==0){
			return true;
		}else{
			return false;
		}
	}
}


実行結果:

2013-11-01
2013-11-1