Classes in this File | Line Coverage | Branch Coverage | Complexity | ||||
DateConverter |
|
| 0.0;0 |
1 | /* | |
2 | * Copyright 2004-2008 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 | package org.seasar.cubby.converter.impl; | |
17 | ||
18 | import java.text.DateFormat; | |
19 | import java.text.ParseException; | |
20 | import java.util.Date; | |
21 | ||
22 | import org.seasar.cubby.converter.ConversionHelper; | |
23 | ||
24 | /** | |
25 | * 任意のオブジェクトから{@link Date}への変換を行うコンバータです。 | |
26 | * <p> | |
27 | * 変換元のオブジェクトの文字列表現をフォーマットに従って{@link Date}に変換した結果を変換先とします。 | |
28 | * </p> | |
29 | * | |
30 | * @author baba | |
31 | * @since 1.1.0 | |
32 | */ | |
33 | 73 | public class DateConverter extends AbstractConverter { |
34 | ||
35 | /** | |
36 | * {@inheritDoc} | |
37 | */ | |
38 | public Class<?> getObjectType() { | |
39 | 83 | return Date.class; |
40 | } | |
41 | ||
42 | /** | |
43 | * {@inheritDoc} | |
44 | */ | |
45 | public Object convertToObject(final Object value, | |
46 | final Class<?> objectType, ConversionHelper helper) { | |
47 | 4 | if (value == null) { |
48 | 0 | return null; |
49 | } | |
50 | 4 | final DateFormat dateFormat = helper.getFormatPattern().getDateFormat(); |
51 | 4 | return toDate(value.toString(), dateFormat); |
52 | } | |
53 | ||
54 | /** | |
55 | * 文字列を{@link Date}に変換して返します。 | |
56 | * | |
57 | * @param date | |
58 | * 変換元のオブジェクトの文字列表現 | |
59 | * @param dateFormat | |
60 | * フォーマット | |
61 | * @return 変換した結果の{@link Date} | |
62 | */ | |
63 | protected Date toDate(final String date, final DateFormat dateFormat) { | |
64 | 4 | if (date == null || date.length() == 0) { |
65 | 0 | return null; |
66 | } | |
67 | try { | |
68 | 4 | return dateFormat.parse(date); |
69 | 0 | } catch (final ParseException e) { |
70 | 0 | return null; |
71 | } | |
72 | } | |
73 | ||
74 | /** | |
75 | * {@inheritDoc} | |
76 | */ | |
77 | public String convertToString(final Object value, ConversionHelper helper) { | |
78 | 1 | if (value == null) { |
79 | 0 | return null; |
80 | } | |
81 | 1 | final DateFormat formatter = helper.getFormatPattern().getDateFormat(); |
82 | 1 | return formatter.format((Date) value); |
83 | } | |
84 | ||
85 | } |