package org.seasar.framework.util;

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

import org.seasar.framework.exception.ParseRuntimeException;

public final class DateConversionUtil {

	private DateConversionUtil() {
	}

	public static Date toDate(Object o) {
		return toDate(o, null);
	}
	
	public static Date toDate(Object o, String pattern) {
		if (o == null) {
			return null;
		} else if (o instanceof String) {
			return toDate((String) o, pattern);
		} else if (o instanceof Date) {
			return (Date) o;
		} else if (o instanceof Calendar) {
			return ((Calendar) o).getTime();
		} else {
			return toDate(o.toString(), pattern);
		}
	}
	
	public static Date toDate(String s, String pattern) {
		SimpleDateFormat sdf = null;
		if (pattern != null) {
			sdf = new SimpleDateFormat(pattern);
		} else {
			sdf = new SimpleDateFormat();
		}
		try {
			return sdf.parse(s);
		} catch (ParseException ex) {
			throw new ParseRuntimeException(ex);
		}
	}
}
