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