日付の演算

以下のような感じ。


package sample.usual;

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

public class DateUtils {

public static void main(String[] args) {
System.out.println("2004-12-10 + 30d: " + addDay("2004-12-10", 30));
System.out.println("2004-02-29 + 01d: " + addDay("2004-02-29", 1));
System.out.println("2004-10-10 + 03m: " + addMonth("2004-10-10", 3));
System.out.println("2004-03-31 + 01m: " + addMonth("2004-03-31", 1));
System.out.println("2002-09-23 + 08y: " + addYear("2002-09-23", 8));
System.out.println("2004-02-29 - 01y: " + addYear("2004-02-29", -1));
}

public static String addYear(String source, int amount) {
return add(source, Calendar.YEAR, amount);
}

public static String addMonth(String source, int amount) {
return add(source, Calendar.MONTH, amount);
}

public static String addDay(String source, int amount) {
return add(source, Calendar.DATE, amount);
}

private static String add(String source, int field, int amount) {
if (source == null || !source.matches("^[0-9]{4}-[0-9]{2}-[0-9]{2}$")) {
return null;
}

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;

try {
date = format.parse(source);
} catch (ParseException e) {
throw new RuntimeException(e);
}

Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(field, amount);

return format.format(cal.getTime());
}

}

実行結果は次の通り。


2004-12-10 + 30d: 2005-01-09
2004-02-29 + 01d: 2004-03-01
2004-10-10 + 03m: 2005-01-10
2004-03-31 + 01m: 2004-04-30
2002-09-23 + 08y: 2010-09-23
2004-02-29 - 01y: 2003-02-28