parse this type of date format in java?

Jonathan picture Jonathan · Oct 25, 2010 · Viewed 10.2k times · Source

what would be the easiest way to parse this date format below in java?:

2010-09-18T10:00:00.000+01:00

i read the DateFormat api in java and could not find a method that takes a string or even this type of date format as a paremeter to parse? When i mean by parse i mean i want to extract the "date (day month and year)", "time" and "timezone" into seperate string objects.

Thanks in advance

Answer

andersoj picture andersoj · Oct 25, 2010

Another answer, since you seem to be focused on simply tearing the String apart (not a good idea, IMHO.) Let's assume the string is valid ISO8601. Can you assume it will always be in the form you cite, or is it just valid 8601? If the latter, you have to cope with a bunch of scenarios as these guys did.

The regex they came up with to validate 8601 alternatives is:

^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])
 (-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])
 ((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?
 ([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$ 

Figuring out how to tease out the correct capture groups makes me woozy. Nevertheless, the following will work for your specific case:

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class Regex8601
{
  static final Pattern r8601 = Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})T((\\d{2}):"+
                               "(\\d{2}):(\\d{2})\\.(\\d{3}))((\\+|-)(\\d{2}):(\\d{2}))");


  //2010-09-18T10:00:00.000+01:00

  public static void main(String[] args)
  {
    String thisdate = "2010-09-18T10:00:00.000+01:00";
    Matcher m = r8601.matcher(thisdate);
    if (m.lookingAt()) {
      System.out.println("Year: "+m.group(1));
      System.out.println("Month: "+m.group(2));
      System.out.println("Day: "+m.group(3));
      System.out.println("Time: "+m.group(4));
      System.out.println("Timezone: "+m.group(9));
    } else {
      System.out.println("no match");
    }
  }
}