/*
 * Copyright 2006-2011 the Seasar Foundation and the Others.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package org.seasar.codegen.lib.internal.impl;

import java.util.Date;

/**
 * 日付を比較するときに時分以下を切り捨て・切り上げするユーティリティクラスです。
 * 
 */
public class FromToOption {

    /**
     * 時分以下を切り捨てします。
     * 
     * @param fromDate
     *            開始日付
     * @return 時分以下を切り捨てしたDate。引数が<code>null</code>の時は<code>null</code>
     */
    public static Date filterFromDate(Date fromDate) {
        if (fromDate == null) {
            return null;
        }
        final java.util.Calendar cal = java.util.Calendar.getInstance();
        cal.setTimeInMillis(fromDate.getTime());
        clearCalendarHourMinuteSecondMilli(cal);
        final java.util.Date cloneDate = (java.util.Date) fromDate.clone();
        cloneDate.setTime(cal.getTimeInMillis());
        return cloneDate;
    }

    /**
     * 時分以下を切り上げします。
     * 
     * @param toDate
     *            終了日付
     * @return 時分以下を切り上げしたDate。引数が<code>null</code>の時は<code>null</code>。
     */
    public static Date filterToDate(Date toDate) {
        if (toDate == null) {
            return null;
        }
        final java.util.Calendar cal = java.util.Calendar.getInstance();
        cal.setTimeInMillis(toDate.getTime());
        clearCalendarHourMinuteSecondMilli(cal);
        addCalendarNextDay(cal);// Key Point!
        final java.util.Date cloneDate = (java.util.Date) toDate.clone();
        cloneDate.setTime(cal.getTimeInMillis());
        return cloneDate;
    }

    private static void addCalendarNextDay(java.util.Calendar cal) {
        cal.add(java.util.Calendar.DAY_OF_MONTH, 1);
    }

    private static void clearCalendarHourMinuteSecondMilli(java.util.Calendar cal) {
        cal.clear(java.util.Calendar.MILLISECOND);
        cal.clear(java.util.Calendar.SECOND);
        cal.clear(java.util.Calendar.MINUTE);
        cal.set(java.util.Calendar.HOUR_OF_DAY, cal.getActualMinimum(java.util.Calendar.HOUR_OF_DAY));
    }
}
