CalendarFormatter.java
01 /*
02  * Copyright 2008-2017 the original author or authors.
03  *
04  * Licensed under the Apache License, Version 2.0 (the "License");
05  * you may not use this file except in compliance with the License.
06  * You may obtain a copy of the License at
07  *
08  *     http://www.apache.org/licenses/LICENSE-2.0
09  *
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 griffon.core.formatters;
17 
18 import javax.annotation.Nonnull;
19 import javax.annotation.Nullable;
20 import java.text.SimpleDateFormat;
21 import java.util.Calendar;
22 
23 import static griffon.util.GriffonNameUtils.isBlank;
24 
25 /**
26  @author Andres Almiray
27  @since 2.0.0
28  */
29 public class CalendarFormatter extends AbstractFormatter<Calendar> {
30     private final SimpleDateFormat dateFormat;
31 
32     public CalendarFormatter() {
33         this(null);
34     }
35 
36     public CalendarFormatter(@Nullable String pattern) {
37         if (isBlank(pattern)) {
38             dateFormat = new SimpleDateFormat();
39         else {
40             dateFormat = new SimpleDateFormat(pattern);
41         }
42     }
43 
44     @Nonnull
45     public String getPattern() {
46         return dateFormat.toPattern();
47     }
48 
49     @Nullable
50     @Override
51     public String format(@Nullable Calendar date) {
52         return date == null null : dateFormat.format(date.getTime());
53     }
54 
55     @Nullable
56     @Override
57     public Calendar parse(@Nullable String strthrows ParseException {
58         if (isBlank(str)) return null;
59         try {
60             Calendar c = Calendar.getInstance();
61             c.setTime(dateFormat.parse(str));
62             return c;
63         catch (java.text.ParseException e) {
64             throw new ParseException(e);
65         }
66     }
67 }