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    /**
035     * Parses a date string returned by the Box API into a {@link Date} object.
036     *
037     * @param dateString a string containing the date.
038     * @return the parsed date.
039     * @throws ParseException if the string cannot be parsed into a valid date.
040     */
041    public static Date parse(String dateString) throws ParseException {
042        try {
043            return THREAD_LOCAL_DATE_FORMAT_SECONDS.get().parse(dateString);
044        } catch (ParseException pe) {
045            try {
046                return THREAD_LOCAL_DATE_FORMAT_MILLISECONDS.get().parse(dateString);
047            } catch (ParseException pe2) {
048                throw pe2;
049            }
050        }
051    }
052
053    /**
054     * Formats a date as a string that can be sent to the Box API.
055     *
056     * @param date the date to format.
057     * @return a string containing the formatted date.
058     */
059    public static String format(Date date) {
060        return THREAD_LOCAL_DATE_FORMAT_SECONDS.get().format(date);
061    }
062
063}