GMTStringToDateConverter.java

package org.gringlobal.spring;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import lombok.extern.slf4j.Slf4j;
import org.gringlobal.util.DateUtils;
import org.springframework.core.convert.converter.Converter;

@Slf4j
public class GMTStringToDateConverter implements Converter<String, Date> {
	private static final String SOAP_DATETIME_EXAMPLE = "2019-11-06T02:22:10.9725936-08:00";
	private static final ThreadLocal<SimpleDateFormat> localDateFormat0 = DateUtils.makeDateFormat("yyyy-MM-dd'T'HH:mm:ss");
	private static final ThreadLocal<SimpleDateFormat> soapDateFormat1 = DateUtils.makeDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
	private static final ThreadLocal<SimpleDateFormat> soapDateFormat2 = DateUtils.makeDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSXXX");

	static {
		log.warn("Current time in SOAP format: {}", soapDateFormat2.get().format(new Date()));
		try {
			soapDateFormat2.get().parse(SOAP_DATETIME_EXAMPLE);
		} catch (final ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public Date convert(final String source) {
		try {
			return soapDateFormat2.get().parse(source);
		} catch (final ParseException e) {
			try {
				return soapDateFormat1.get().parse(source);
			} catch (final ParseException e1) {
				try {
					return localDateFormat0.get().parse(source);
				} catch (final ParseException e2) {
					throw new IllegalArgumentException("Invalid date value " + source, e2);
				}
			}
		}
	}

}