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