jp.terasoluna.fw.util.DateUtil.java Source code

Java tutorial

Introduction

Here is the source code for jp.terasoluna.fw.util.DateUtil.java

Source

/*
 * Copyright (c) 2007 NTT DATA Corporation
 *
 * 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 jp.terasoluna.fw.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * ?
 *
 */
public class DateUtil {

    /**
     * 
     */
    private static Log log = LogFactory.getLog(DateUtil.class);

    /**
     * ??
     *
     * <p>Web??AP???????????
     * ???????????
     * ??????????????
     * ?????????????</p>
     *
     * @deprecated static?Java????????{@code java.util.Calendar}???Joda-Time?{@code org.joda.time.DateTime}???API??????????
     * @return 
     */
    @Deprecated
    public static java.util.Date getSystemTime() {
        Calendar calendar = Calendar.getInstance();
        return calendar.getTime();
    }

    /**
     * java.util.Date?????
     * ??
     *
     * <p>
     *  ApplicationResources.properties
     *  ?????????
     *  ???????<br>
     *  ??????????
     *  ??
     *  <strong> ApplicationResources.properties ?
     *  ?</strong><br>
     *  <code><pre>
     *  wareki.gengo.0.name = ?
     *  wareki.gengo.0.roman = H
     *  wareki.gengo.0.startDate = 1989/01/08
     *  wareki.gengo.1.name = 
     *  wareki.gengo.1.roman = S
     *  wareki.gengo.1.startDate = 1926/12/25
     *  wareki.gengo.2.name = 
     *  wareki.gengo.2.roman = T
     *  wareki.gengo.2.startDate = 1912/07/30
     *  wareki.gengo.3.name = 
     *  wareki.gengo.3.roman = M
     *  wareki.gengo.3.startDate = 1868/09/04
     *  </pre></code>
     * </p>
     *
     * <strong></strong><br>
     * <p>??java.text.SimpleDateFormat ?
     * <i></i> ?????????
     * ? SimpleDateFormat ??
     * </p>
     *
     * <div width="90%" align="center">
     *  <table border="1">
     *   <tr>
     *    <th>?</th>
     *    <th><code>&nbsp;SimpleDateFormat</code>&nbsp;</th>
     *    <th><code>&nbsp;dateToWarekiString()</code>&nbsp;</th>
     *   </tr>
     *   <tr>
     *    <td>G</td>
     *    <td align="left"><br><br><br>AD</td>
     *    <td align="left">?<br><br>
     *                     <br>
     *                    4???<br>
     *                     ????<br>
     *                     3???<br>
     *                     M?T?S?H</td>
     *   </tr>
     *   <tr>
     *    <td>y</td>
     *    <td align="left"><br><br><br>2002</td>
     *    <td align="left"><br><br><br>14</td>
     *   </tr>
     *   <tr>
     *    <td>E</td>
     *    <td align="left"><br><br><br>Tuesday</td>
     *    <td align="left"><br><br>
     *                     <br>
     *                    4???<br>
     *                     ???<br>
     *                     3???<br>
     *                     ???</td>
     *   </tr>
     * </table>
     * </div>
     *
     * <p>?????E????? SimpleDateFotmat
     * ???? &quot;ja&quot;
     * ???????</p>
     *
     * <p>????????????getWarekiGengoName()?
     * getWarekiGengoRoman()?getWarekiYear() ?????
     * ????????AplicationResources ?
     * ????</p>
     *
     * <p><code><pre>
     * wareki.gengo.<i>ID</i>.name=<i>???</i>
     * wareki.gengo.<i>ID</i>.roman=<i>??</i>
     * wareki.gengo.<i>ID</i>.startDate=<i>?:yyyy/MM/dd?</i>
     * </pre></code></p>
     *
     * <p>ID????????????????
     * ???</p>
     *
     * @param format 
     * @param date ???
     * @return ?????
     */
    public static String dateToWarekiString(String format, java.util.Date date) {

        // SimpleDateFormat?????'G'???'y'?
        // ???
        StringBuilder sb = new StringBuilder();
        boolean inQuote = false; // ???????
        char prevCh = 0;
        int count = 0;
        for (int i = 0; i < format.length(); i++) {
            char ch = format.charAt(i);
            if (ch != prevCh && count > 0) {
                if (prevCh == 'G' && count >= 4) {
                    sb.append(getWarekiGengoName(date));
                } else if (prevCh == 'G') {
                    // ???????????
                    sb.append('\'');
                    sb.append(getWarekiGengoRoman(date));
                    sb.append('\'');
                } else if (prevCh == 'y') {
                    sb.append(getWarekiYear(date));
                }
                count = 0;
            }

            if (ch == '\'') {
                sb.append('\'');
                inQuote = !inQuote;
            } else if (!inQuote && (ch == 'G' || ch == 'y')) {
                // ch??????????
                // ??
                prevCh = ch;
                ++count;
            } else {
                // ????????
                sb.append(ch);
            }
        }

        // ????
        if (count > 0) {
            if (prevCh == 'G' && count >= 4) {
                sb.append(getWarekiGengoName(date));
            } else if (prevCh == 'G') {
                sb.append('\'');
                sb.append(getWarekiGengoRoman(date));
                sb.append('\'');
            } else if (prevCh == 'y') {
                sb.append(getWarekiYear(date));
            }
        }

        SimpleDateFormat sdf = new SimpleDateFormat(sb.toString(), Locale.JAPAN);

        sdf.getCalendar().setLenient(false);
        sdf.setLenient(false);
        return sdf.format(date);
    }

    /**
     * ApplicationResources ?????
     * ????
     */
    private static final String GENGO_KEY = "wareki.gengo.";

    /**
     * ???????
     */
    private static final Map<Date, String> GENGO_NAME = new HashMap<Date, String>();

    /**
     * ??????
     */
    private static final Map<Date, String> GENGO_ROMAN = new HashMap<Date, String>();

    /**
     * ??????????
     * ????
     */
    private static final Date[] GENGO_BEGIN_DATES;

    /**
     * ??????????
     * ????
     */
    private static final int[] GENGO_BEGIN_YEARS;

    /**
     * ??ApplicationResources ???
     * ?????
     */
    static {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

        // ??????????
        Enumeration<String> enumaration = PropertyUtil.getPropertyNames(GENGO_KEY);
        Set<String> ids = new HashSet<String>();

        GENGO_LOOP: while (enumaration.hasMoreElements()) {
            String key = enumaration.nextElement();
            String id = key.substring(GENGO_KEY.length(), key.lastIndexOf("."));
            if (!ids.contains(id)) {
                String name = PropertyUtil.getProperty(GENGO_KEY + id + ".name", "");
                String roman = PropertyUtil.getProperty(GENGO_KEY + id + ".roman", "");

                String start = PropertyUtil.getProperty(GENGO_KEY + id + ".startDate");
                if (start == null) {
                    log.error(GENGO_KEY + id + ".startDate not found");
                    continue GENGO_LOOP;
                }

                try {
                    Date date = sdf.parse(start);

                    GENGO_NAME.put(date, name);
                    GENGO_ROMAN.put(date, roman);
                    log.info("registerd: " + date + ", " + name + ", " + roman);
                } catch (ParseException e) {
                    log.error(e.getMessage());
                }

                ids.add(id);
            }
        }

        // ????????????
        Set<Date> keySet = GENGO_NAME.keySet();
        int size = keySet.size();
        GENGO_BEGIN_DATES = keySet.toArray(new Date[size]);
        Arrays.sort(GENGO_BEGIN_DATES);

        // ???????????????
        GENGO_BEGIN_YEARS = new int[size];
        Calendar calendar = Calendar.getInstance();
        for (int i = 0; i < GENGO_BEGIN_DATES.length; i++) {
            calendar.setTime(GENGO_BEGIN_DATES[i]);
            GENGO_BEGIN_YEARS[i] = calendar.get(Calendar.YEAR);
        }
    }

    /**
     * ??????
     *
     * <p>
     * ???ApplicationResources ??
     * </p>
     *
     * @param date 
     * @return ?
     */
    public static String getWarekiGengoName(Date date) {
        for (int i = GENGO_BEGIN_DATES.length - 1; i >= 0; i--) {
            if (!date.before(GENGO_BEGIN_DATES[i])) {
                return GENGO_NAME.get(GENGO_BEGIN_DATES[i]);
            }
        }
        throw new IllegalArgumentException("Wareki Gengo Name not found for " + date);
    }

    /**
     * ???????
     *
     * <p>????ApplicationResources??</p>
     *
     * @param date 
     * @return ??
     */
    public static String getWarekiGengoRoman(Date date) {
        for (int i = GENGO_BEGIN_DATES.length - 1; i >= 0; i--) {
            if (!date.before(GENGO_BEGIN_DATES[i])) {
                return GENGO_ROMAN.get(GENGO_BEGIN_DATES[i]);
            }
        }
        throw new IllegalArgumentException("Wareki Gengo Roman not found for " + date);
    }

    /**
     * ?????
     *
     * @param date 
     * @return 
     */
    public static int getWarekiYear(Date date) {
        for (int i = GENGO_BEGIN_DATES.length - 1; i >= 0; i--) {
            if (!date.before(GENGO_BEGIN_DATES[i])) {
                Calendar calendar = Calendar.getInstance();

                calendar.setTime(date);
                int year = calendar.get(Calendar.YEAR);

                return year - GENGO_BEGIN_YEARS[i] + 1;
            }
        }
        throw new IllegalArgumentException("Wareki Gengo not found for " + date);
    }

}