KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > binding > format > support > DateFormatter


1 /*
2  * Copyright 2002-2006 the original author or authors.
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, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.springframework.binding.format.support;
17
18 import java.text.DateFormat JavaDoc;
19 import java.text.ParseException JavaDoc;
20 import java.util.Date JavaDoc;
21
22 import org.springframework.binding.format.InvalidFormatException;
23
24 /**
25  * Formatter that formats date objects.
26  * @author Keith Donald
27  */

28 public class DateFormatter extends AbstractFormatter {
29
30     private DateFormat JavaDoc dateFormat;
31
32     /**
33      * Constructs a date formatter that will delegate to the specified date
34      * format.
35      * @param dateFormat
36      */

37     public DateFormatter(DateFormat JavaDoc dateFormat) {
38         super();
39         this.dateFormat = dateFormat;
40     }
41
42     /**
43      * Constructs a date formatter that will delegate to the specified date
44      * format.
45      * @param dateFormat
46      * @param allowEmpty should this formatter allow empty input arguments?
47      */

48     public DateFormatter(DateFormat JavaDoc dateFormat, boolean allowEmpty) {
49         super(allowEmpty);
50         this.dateFormat = dateFormat;
51     }
52
53     // convert from date to string
54
protected String JavaDoc doFormatValue(Object JavaDoc date) {
55         return dateFormat.format((Date JavaDoc)date);
56     }
57
58     // convert back from string to date
59
protected Object JavaDoc doParseValue(String JavaDoc formattedString, Class JavaDoc targetClass) throws ParseException JavaDoc {
60         return dateFormat.parse(formattedString);
61     }
62
63     public Date JavaDoc parseDate(String JavaDoc formattedString) throws InvalidFormatException {
64         return (Date JavaDoc)parseValue(formattedString, Date JavaDoc.class);
65     }
66 }
Popular Tags