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 = new ThreadLocal<DateFormat>() {
014        @Override
015        protected DateFormat initialValue() {
016            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
017            sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
018            return sdf;
019        }
020    };
021
022    private BoxDateFormat() { }
023
024    /**
025     * Parses a date string returned by the Box API into a {@link Date} object.
026     * @param  dateString     a string containing the date.
027     * @return                the parsed date.
028     * @throws ParseException if the string cannot be parsed into a valid date.
029     */
030    public static Date parse(String dateString) throws ParseException {
031        return THREAD_LOCAL_DATE_FORMAT.get().parse(fixIso8601TimeZone(dateString));
032    }
033
034    /**
035     * Formats a date as a string that can be sent to the Box API.
036     * @param  date the date to format.
037     * @return      a string containing the formatted date.
038     */
039    public static String format(Date date) {
040        return THREAD_LOCAL_DATE_FORMAT.get().format(date);
041    }
042
043    /**
044     * Helper function to handle ISO 8601 strings of the following format:
045     * "2008-03-01T13:00:00+01:00".  Note that the final colon (":") in the
046     * time zone is not supported by SimpleDateFormat's "Z" token.
047     *
048     * @param dateString a string containing the date.
049     * @return a date string that matches the date format.
050     */
051    private static String fixIso8601TimeZone(String dateString) {
052        if (dateString.length() >= 24 && dateString.charAt(22) == ':') {
053            return dateString.substring(0, 22) + dateString.substring(23);
054        }
055        return dateString;
056    }
057}