LocalDateTimeFormatter.java
01 /*
02  * Copyright 2008-2016 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.time.LocalDateTime;
21 import java.time.format.DateTimeFormatter;
22 import java.time.format.DateTimeParseException;
23 
24 import static griffon.util.GriffonNameUtils.isBlank;
25 
26 /**
27  @author Andres Almiray
28  @since 2.4.0
29  */
30 public class LocalDateTimeFormatter extends AbstractFormatter<LocalDateTime> {
31     private final DateTimeFormatter formatter;
32     private final String pattern;
33 
34     public LocalDateTimeFormatter() {
35         this(null);
36     }
37 
38     public LocalDateTimeFormatter(@Nullable String pattern) {
39         if (isBlank(pattern)) {
40             formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
41             this.pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS";
42         else {
43             formatter = DateTimeFormatter.ofPattern(pattern);
44             this.pattern = pattern;
45         }
46     }
47 
48     @Nonnull
49     public String getPattern() {
50         return pattern;
51     }
52 
53     @Nullable
54     public String format(@Nullable LocalDateTime time) {
55         return time == null null : formatter.format(time);
56     }
57 
58     @Nullable
59     @Override
60     public LocalDateTime parse(@Nullable String strthrows ParseException {
61         if (isBlank(str)) return null;
62         try {
63             return LocalDateTime.parse(str, formatter);
64         catch (DateTimeParseException e) {
65             throw new ParseException(e);
66         }
67     }
68 }