View Javadoc

1   /*
2    * Copyright 2004-2010 the Seasar Foundation and the Others.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  
17  package org.seasar.cubby.converter.impl;
18  
19  import java.text.DateFormat;
20  import java.text.ParseException;
21  import java.text.ParsePosition;
22  import java.text.SimpleDateFormat;
23  import java.util.Date;
24  
25  import org.seasar.cubby.action.MessageInfo;
26  import org.seasar.cubby.converter.ConversionException;
27  
28  /**
29   * 文字列を日付型のオブジェクトに変換するクラスの抽象クラスです。
30   * 
31   * @author baba
32   */
33  public abstract class AbstractDateConverter extends AbstractConverter {
34  
35  	/**
36  	 * 文字列を{@link Date}に変換して返します。
37  	 * 
38  	 * @param value
39  	 *            変換元のオブジェクトの文字列表現
40  	 * @param pattern
41  	 *            日付と時刻のフォーマットを記述するパターン
42  	 * @return 変換した結果の{@link Date}
43  	 * @throws ConversionException
44  	 *             {@link ParseException} が発生した場合
45  	 * @see SimpleDateFormat#parse(String, ParsePosition)
46  	 */
47  	protected Date toDate(final String value, final String pattern)
48  			throws ConversionException {
49  		if (value == null || value.length() == 0) {
50  			return null;
51  		}
52  
53  		final ParsePosition parsePosition = new ParsePosition(0);
54  		final DateFormat dateFormat = new SimpleDateFormat(pattern);
55  		dateFormat.setLenient(false);
56  		final Date date = dateFormat.parse(value, parsePosition);
57  		if (date != null && parsePosition.getIndex() == value.length()) {
58  			return date;
59  		}
60  
61  		final MessageInfo messageInfo = new MessageInfo();
62  		messageInfo.setKey("valid.dateFormat");
63  		throw new ConversionException(messageInfo);
64  	}
65  
66  	/**
67  	 * 指定された日付を文字列に変換します。
68  	 * 
69  	 * @param date
70  	 *            日付
71  	 * @param pattern
72  	 *            日付と時刻のフォーマットを記述するパターン
73  	 * @return 指定された日付をフォーマットした文字列
74  	 */
75  	protected String toString(final Date date, final String pattern) {
76  		final DateFormat dateFormat = new SimpleDateFormat(pattern);
77  		return dateFormat.format(date);
78  	}
79  
80  }