public static Calendar toCalendar(String date) throws IOException {
Calendar retval = null;
if( date != null && date.trim().length() > 0 )
{
//these are the default values
int year = 0;
int month = 1;
int day = 1;
int hour = 0;
int minute = 0;
int second = 0;
//first string off the prefix if it exists
try
{
SimpleTimeZone zone = null;
if( date.startsWith( "D:" ) )
{
date = date.substring( 2, date.length() );
}
date = date.replaceAll("[-:T]", "");
if( date.length() < 4 )
{
throw new IOException( "Error: Invalid date format '" + date + "'" );
}
year = Integer.parseInt( date.substring( 0, 4 ) );
if( date.length() >= 6 )
{
month = Integer.parseInt( date.substring( 4, 6 ) );
}
if( date.length() >= 8 )
{
day = Integer.parseInt( date.substring( 6, 8 ) );
}
if( date.length() >= 10 )
{
hour = Integer.parseInt( date.substring( 8, 10 ) );
}
if( date.length() >= 12 )
{
minute = Integer.parseInt( date.substring( 10, 12 ) );
}
if( date.length() >= 14 )
{
second = Integer.parseInt( date.substring( 12, 14 ) );
}
if( date.length() >= 15 )
{
char sign = date.charAt( 14 );
if( sign == 'Z' )
{
zone = new SimpleTimeZone(0,"Unknown");
}
else
{
int hours = 0;
int minutes = 0;
if( date.length() >= 17 )
{
if( sign == '+' )
{
//parseInt cannot handle the + sign
hours = Integer.parseInt( date.substring( 15, 17 ) );
}
else
{
hours = -Integer.parseInt( date.substring( 14, 16 ) );
}
}
if( sign=='+' )
{
if( date.length() >= 19 )
{
minutes = Integer.parseInt( date.substring( 17, 19 ) );
}
}
else
{
if( date.length() >= 18 )
{
minutes = Integer.parseInt( date.substring( 16, 18 ) );
}
}
zone = new SimpleTimeZone( hours*60*60*1000 + minutes*60*1000, "Unknown" );
}
}
if( zone == null )
{
retval = new GregorianCalendar();
}
else
{
retval = new GregorianCalendar( zone );
}
retval.clear();
retval.set( year, month-1, day, hour, minute, second );
}
catch( NumberFormatException e )
{
// remove the arbitrary : in the timezone. SimpleDateFormat
// can't handle it
if (date.substring(date.length()-3,date.length()-2).equals(":") &&
(date.substring(date.length()-6,date.length()-5).equals("+") ||
date.substring(date.length()-6,date.length()-5).equals("-")))
{
//thats a timezone string, remove the :
date = date.substring(0,date.length()-3) +
date.substring(date.length()-2);
}
for( int i=0; retval == null && i< POTENTIAL_FORMATS.length; i++ )
{
try
{
Date utilDate = POTENTIAL_FORMATS[i].parse( date );
retval = new GregorianCalendar();
retval.setTime( utilDate );
}
catch( ParseException pe )
{
//ignore and move to next potential format
}
}
if( retval == null )
{
//we didn't find a valid date format so throw an exception
throw new IOException( "Error converting date:" + date );
}
}
}
return retval;
}
This will convert a string to a calendar. |