View Javadoc

1   /*
2    * $Id: DateFormatter.java 768855 2009-04-27 02:09:35Z wesw $
3    *
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *  http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  package org.apache.struts2.util;
23  
24  import java.text.DateFormat;
25  import java.text.ParseException;
26  import java.text.SimpleDateFormat;
27  import java.util.Date;
28  
29  
30  /***
31   * A bean that can be used to format dates
32   *
33   */
34  public class DateFormatter {
35  
36      Date date;
37      DateFormat format;
38  
39      // Attributes ----------------------------------------------------
40      DateFormat parser;
41  
42  
43      // Public --------------------------------------------------------
44      public DateFormatter() {
45          this.parser = new SimpleDateFormat();
46          this.format = new SimpleDateFormat();
47          this.date = new Date();
48      }
49  
50  
51      public void setDate(String date) {
52          try {
53              this.date = parser.parse(date);
54          } catch (ParseException e) {
55              throw new IllegalArgumentException(e.getMessage());
56          }
57      }
58  
59      public void setDate(Date date) {
60          this.date = (date == null) ? null : (Date)date.clone();
61      }
62  
63      public void setDate(int date) {
64          setDate(Integer.toString(date));
65      }
66  
67      public Date getDate() {
68          return this.date;
69      }
70  
71      public void setFormat(String format) {
72          this.format = new SimpleDateFormat(format);
73      }
74  
75      public void setFormat(DateFormat format) {
76          this.format = format;
77      }
78  
79      public String getFormattedDate() {
80          return format.format(date);
81      }
82  
83      public void setParseFormat(String format) {
84          this.parser = new SimpleDateFormat(format);
85      }
86  
87      public void setParser(DateFormat parser) {
88          this.parser = parser;
89      }
90  
91      public void setTime(long time) {
92          date.setTime(time);
93      }
94  }