001/*
002 * Copyright 2002-2018 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.format.datetime;
018
019import java.text.DateFormat;
020import java.text.ParseException;
021import java.text.SimpleDateFormat;
022import java.util.Collections;
023import java.util.Date;
024import java.util.EnumMap;
025import java.util.Locale;
026import java.util.Map;
027import java.util.TimeZone;
028
029import org.springframework.format.Formatter;
030import org.springframework.format.annotation.DateTimeFormat.ISO;
031import org.springframework.lang.Nullable;
032import org.springframework.util.StringUtils;
033
034/**
035 * A formatter for {@link java.util.Date} types.
036 * Allows the configuration of an explicit date pattern and locale.
037 *
038 * @author Keith Donald
039 * @author Juergen Hoeller
040 * @author Phillip Webb
041 * @since 3.0
042 * @see SimpleDateFormat
043 */
044public class DateFormatter implements Formatter<Date> {
045
046        private static final TimeZone UTC = TimeZone.getTimeZone("UTC");
047
048        private static final Map<ISO, String> ISO_PATTERNS;
049
050        static {
051                Map<ISO, String> formats = new EnumMap<>(ISO.class);
052                formats.put(ISO.DATE, "yyyy-MM-dd");
053                formats.put(ISO.TIME, "HH:mm:ss.SSSXXX");
054                formats.put(ISO.DATE_TIME, "yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
055                ISO_PATTERNS = Collections.unmodifiableMap(formats);
056        }
057
058
059        @Nullable
060        private String pattern;
061
062        private int style = DateFormat.DEFAULT;
063
064        @Nullable
065        private String stylePattern;
066
067        @Nullable
068        private ISO iso;
069
070        @Nullable
071        private TimeZone timeZone;
072
073        private boolean lenient = false;
074
075
076        /**
077         * Create a new default DateFormatter.
078         */
079        public DateFormatter() {
080        }
081
082        /**
083         * Create a new DateFormatter for the given date pattern.
084         */
085        public DateFormatter(String pattern) {
086                this.pattern = pattern;
087        }
088
089
090        /**
091         * Set the pattern to use to format date values.
092         * <p>If not specified, DateFormat's default style will be used.
093         */
094        public void setPattern(String pattern) {
095                this.pattern = pattern;
096        }
097
098        /**
099         * Set the ISO format used for this date.
100         * @param iso the {@link ISO} format
101         * @since 3.2
102         */
103        public void setIso(ISO iso) {
104                this.iso = iso;
105        }
106
107        /**
108         * Set the style to use to format date values.
109         * <p>If not specified, DateFormat's default style will be used.
110         * @see DateFormat#DEFAULT
111         * @see DateFormat#SHORT
112         * @see DateFormat#MEDIUM
113         * @see DateFormat#LONG
114         * @see DateFormat#FULL
115         */
116        public void setStyle(int style) {
117                this.style = style;
118        }
119
120        /**
121         * Set the two character to use to format date values. The first character used for
122         * the date style, the second is for the time style. Supported characters are
123         * <ul>
124         * <li>'S' = Small</li>
125         * <li>'M' = Medium</li>
126         * <li>'L' = Long</li>
127         * <li>'F' = Full</li>
128         * <li>'-' = Omitted</li>
129         * </ul>
130         * This method mimics the styles supported by Joda-Time.
131         * @param stylePattern two characters from the set {"S", "M", "L", "F", "-"}
132         * @since 3.2
133         */
134        public void setStylePattern(String stylePattern) {
135                this.stylePattern = stylePattern;
136        }
137
138        /**
139         * Set the TimeZone to normalize the date values into, if any.
140         */
141        public void setTimeZone(TimeZone timeZone) {
142                this.timeZone = timeZone;
143        }
144
145        /**
146         * Specify whether or not parsing is to be lenient. Default is false.
147         * <p>With lenient parsing, the parser may allow inputs that do not precisely match the format.
148         * With strict parsing, inputs must match the format exactly.
149         */
150        public void setLenient(boolean lenient) {
151                this.lenient = lenient;
152        }
153
154
155        @Override
156        public String print(Date date, Locale locale) {
157                return getDateFormat(locale).format(date);
158        }
159
160        @Override
161        public Date parse(String text, Locale locale) throws ParseException {
162                return getDateFormat(locale).parse(text);
163        }
164
165
166        protected DateFormat getDateFormat(Locale locale) {
167                DateFormat dateFormat = createDateFormat(locale);
168                if (this.timeZone != null) {
169                        dateFormat.setTimeZone(this.timeZone);
170                }
171                dateFormat.setLenient(this.lenient);
172                return dateFormat;
173        }
174
175        private DateFormat createDateFormat(Locale locale) {
176                if (StringUtils.hasLength(this.pattern)) {
177                        return new SimpleDateFormat(this.pattern, locale);
178                }
179                if (this.iso != null && this.iso != ISO.NONE) {
180                        String pattern = ISO_PATTERNS.get(this.iso);
181                        if (pattern == null) {
182                                throw new IllegalStateException("Unsupported ISO format " + this.iso);
183                        }
184                        SimpleDateFormat format = new SimpleDateFormat(pattern);
185                        format.setTimeZone(UTC);
186                        return format;
187                }
188                if (StringUtils.hasLength(this.stylePattern)) {
189                        int dateStyle = getStylePatternForChar(0);
190                        int timeStyle = getStylePatternForChar(1);
191                        if (dateStyle != -1 && timeStyle != -1) {
192                                return DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale);
193                        }
194                        if (dateStyle != -1) {
195                                return DateFormat.getDateInstance(dateStyle, locale);
196                        }
197                        if (timeStyle != -1) {
198                                return DateFormat.getTimeInstance(timeStyle, locale);
199                        }
200                        throw new IllegalStateException("Unsupported style pattern '" + this.stylePattern + "'");
201
202                }
203                return DateFormat.getDateInstance(this.style, locale);
204        }
205
206        private int getStylePatternForChar(int index) {
207                if (this.stylePattern != null && this.stylePattern.length() > index) {
208                        switch (this.stylePattern.charAt(index)) {
209                                case 'S': return DateFormat.SHORT;
210                                case 'M': return DateFormat.MEDIUM;
211                                case 'L': return DateFormat.LONG;
212                                case 'F': return DateFormat.FULL;
213                                case '-': return -1;
214                        }
215                }
216                throw new IllegalStateException("Unsupported style pattern '" + this.stylePattern + "'");
217        }
218
219}