001package com.box.sdk;
002
003import java.text.DateFormat;
004import java.text.ParseException;
005import java.text.SimpleDateFormat;
006import java.util.Date;
007import java.util.TimeZone;
008
009/**
010 * Contains methods for parsing and formatting dates for use with the Box API.
011 */
012public final class BoxDateFormat {
013    private static final ThreadLocal<DateFormat> THREAD_LOCAL_DATE_FORMAT_SECONDS = new ThreadLocal<DateFormat>() {
014        @Override
015        protected DateFormat initialValue() {
016            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
017            sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
018            return sdf;
019        }
020    };
021
022    private static final ThreadLocal<DateFormat> THREAD_LOCAL_DATE_FORMAT_MILLISECONDS = new ThreadLocal<DateFormat>() {
023        @Override
024        protected DateFormat initialValue() {
025            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
026            sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
027            return sdf;
028        }
029    };
030
031    private BoxDateFormat() { }
032
033    /**
034     * Parses a date string returned by the Box API into a {@link Date} object.
035     * @param  dateString     a string containing the date.
036     * @return                the parsed date.
037     * @throws ParseException if the string cannot be parsed into a valid date.
038     */
039    public static Date parse(String dateString) throws ParseException {
040        try {
041            return THREAD_LOCAL_DATE_FORMAT_SECONDS.get().parse(dateString);
042        } catch (ParseException pe) {
043            try {
044                return THREAD_LOCAL_DATE_FORMAT_MILLISECONDS.get().parse(dateString);
045            } catch (ParseException pe2) {
046                throw pe2;
047            }
048        }
049    }
050
051    /**
052     * Formats a date as a string that can be sent to the Box API.
053     * @param  date the date to format.
054     * @return      a string containing the formatted date.
055     */
056    public static String format(Date date) {
057        return THREAD_LOCAL_DATE_FORMAT_SECONDS.get().format(date);
058    }
059
060}