CalendarFormatter.java
01 /*
02  * SPDX-License-Identifier: Apache-2.0
03  *
04  * Copyright 2008-2017 the original author or authors.
05  *
06  * Licensed under the Apache License, Version 2.0 (the "License");
07  * you may not use this file except in compliance with the License.
08  * You may obtain a copy of the License at
09  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18 package griffon.core.formatters;
19 
20 import javax.annotation.Nonnull;
21 import javax.annotation.Nullable;
22 import java.text.SimpleDateFormat;
23 import java.util.Calendar;
24 
25 import static griffon.util.GriffonNameUtils.isBlank;
26 
27 /**
28  @author Andres Almiray
29  @since 2.0.0
30  */
31 public class CalendarFormatter extends AbstractFormatter<Calendar> {
32     private final SimpleDateFormat dateFormat;
33 
34     public CalendarFormatter() {
35         this(null);
36     }
37 
38     public CalendarFormatter(@Nullable String pattern) {
39         if (isBlank(pattern)) {
40             dateFormat = new SimpleDateFormat();
41         else {
42             dateFormat = new SimpleDateFormat(pattern);
43         }
44     }
45 
46     @Nonnull
47     public String getPattern() {
48         return dateFormat.toPattern();
49     }
50 
51     @Nullable
52     @Override
53     public String format(@Nullable Calendar date) {
54         return date == null null : dateFormat.format(date.getTime());
55     }
56 
57     @Nullable
58     @Override
59     public Calendar parse(@Nullable String strthrows ParseException {
60         if (isBlank(str)) return null;
61         try {
62             Calendar c = Calendar.getInstance();
63             c.setTime(dateFormat.parse(str));
64             return c;
65         catch (java.text.ParseException e) {
66             throw new ParseException(e);
67         }
68     }
69 }