01 /*
02 * Copyright 2008-2014 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 public String format(@Nullable Calendar date) {
51 return date == null ? null : dateFormat.format(date.getTime());
52 }
53
54 @Nullable
55 @Override
56 public Calendar parse(@Nullable String str) throws ParseException {
57 if (isBlank(str)) return null;
58 try {
59 Calendar c = Calendar.getInstance();
60 c.setTime(dateFormat.parse(str));
61 return c;
62 } catch (java.text.ParseException e) {
63 throw new ParseException(e);
64 }
65 }
66 }
|