| 
01 /*02  * Copyright 2008-2015 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.Date;
 22
 23 import static griffon.util.GriffonNameUtils.isBlank;
 24
 25 /**
 26  * @author Andres Almiray
 27  * @since 2.0.0
 28  */
 29 public class DateFormatter extends AbstractFormatter<Date> {
 30     private final SimpleDateFormat dateFormat;
 31
 32     public DateFormatter() {
 33         this(null);
 34     }
 35
 36     public DateFormatter(@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 Date date) {
 51         return date == null ? null : dateFormat.format(date);
 52     }
 53
 54     @Nullable
 55     @Override
 56     public Date parse(@Nullable String str) throws ParseException {
 57         if (isBlank(str)) return null;
 58         try {
 59             return dateFormat.parse(str);
 60         } catch (java.text.ParseException e) {
 61             throw new ParseException(e);
 62         }
 63     }
 64 }
 |