001package com.box.sdk; 002 003import java.text.DateFormat; 004import java.text.ParseException; 005import java.text.SimpleDateFormat; 006import java.util.Date; 007 008/** 009 * Contains methods for parsing and formatting dates for use with the Box API. 010 */ 011public final class BoxDateFormat { 012 private static final ThreadLocal<DateFormat> THREAD_LOCAL_DATE_FORMAT = new ThreadLocal<DateFormat>() { 013 @Override 014 protected DateFormat initialValue() { 015 return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); 016 } 017 }; 018 019 private BoxDateFormat() { } 020 021 /** 022 * Parses a date string returned by the Box API into a {@link Date} object. 023 * @param dateString a string containing the date. 024 * @return the parsed date. 025 * @throws ParseException if the string cannot be parsed into a valid date. 026 */ 027 public static Date parse(String dateString) throws ParseException { 028 return THREAD_LOCAL_DATE_FORMAT.get().parse(fixIso8601TimeZone(dateString)); 029 } 030 031 /** 032 * Formats a date as a string that can be sent to the Box API. 033 * @param date the date to format. 034 * @return a string containing the formatted date. 035 */ 036 public static String format(Date date) { 037 return THREAD_LOCAL_DATE_FORMAT.get().format(date); 038 } 039 040 /** 041 * Helper function to handle ISO 8601 strings of the following format: 042 * "2008-03-01T13:00:00+01:00". Note that the final colon (":") in the 043 * time zone is not supported by SimpleDateFormat's "Z" token. 044 * 045 * @param dateString a string containing the date. 046 * @return a date string that matches the date format. 047 */ 048 private static String fixIso8601TimeZone(String dateString) { 049 if (dateString.length() >= 24 && dateString.charAt(22) == ':') { 050 return dateString.substring(0, 22) + dateString.substring(23); 051 } 052 return dateString; 053 } 054}