001/*
002 * Copyright 2002-2016 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.standard;
018
019import java.text.ParseException;
020import java.time.Instant;
021import java.time.format.DateTimeFormatter;
022import java.util.Locale;
023
024import org.springframework.format.Formatter;
025import org.springframework.lang.UsesJava8;
026
027/**
028 * {@link Formatter} implementation for a JSR-310 {@link java.time.Instant},
029 * following JSR-310's parsing rules for an Instant (that is, not using a
030 * configurable {@link java.time.format.DateTimeFormatter}): accepting the
031 * default {@code ISO_INSTANT} format as well as {@code RFC_1123_DATE_TIME}
032 * (which is commonly used for HTTP date header values), as of Spring 4.3.
033 *
034 * @author Juergen Hoeller
035 * @since 4.0
036 * @see java.time.Instant#parse
037 * @see java.time.format.DateTimeFormatter#ISO_INSTANT
038 * @see java.time.format.DateTimeFormatter#RFC_1123_DATE_TIME
039 */
040@UsesJava8
041public class InstantFormatter implements Formatter<Instant> {
042
043        @Override
044        public Instant parse(String text, Locale locale) throws ParseException {
045                if (text.length() > 0 && Character.isDigit(text.charAt(0))) {
046                        // assuming UTC instant a la "2007-12-03T10:15:30.00Z"
047                        return Instant.parse(text);
048                }
049                else {
050                        // assuming RFC-1123 value a la "Tue, 3 Jun 2008 11:05:30 GMT"
051                        return Instant.from(DateTimeFormatter.RFC_1123_DATE_TIME.parse(text));
052                }
053        }
054
055        @Override
056        public String print(Instant object, Locale locale) {
057                return object.toString();
058        }
059
060}