Java tutorial
//package com.java2s; import java.util.Date; import java.util.GregorianCalendar; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { /** * Pattern used for matching the XsDateTime formatted timestamp strings */ protected static final Pattern xsDtPattern = Pattern .compile("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(\\.(\\d{3}))?(.+)?"); /** * Calendar instance used for calculating dates for timestamps */ protected static GregorianCalendar cal = new GregorianCalendar(); /** * Expects an XML xs:dateTime lexical format string, as in * <code>2005-10-24T11:57:31.000+01:00</code>. Some bad MXML files miss * timezone or milliseconds information, thus a certain amount of tolerance * is applied towards malformed timestamp string representations. If * unparseable, this method will return <code>null</code>. * * @param xmlLexicalString * @return */ public static Date parseXsDateTime(String xsDateTime) { // match pattern against timestamp string Matcher matcher = xsDtPattern.matcher(xsDateTime); if (matcher.matches() == true) { // extract data particles from matched groups / subsequences int year = Integer.parseInt(matcher.group(1)); int month = Integer.parseInt(matcher.group(2)) - 1; int day = Integer.parseInt(matcher.group(3)); int hour = Integer.parseInt(matcher.group(4)); int minute = Integer.parseInt(matcher.group(5)); int second = Integer.parseInt(matcher.group(6)); int millis = 0; // probe for successful parsing of milliseconds if (matcher.group(7) != null) { millis = Integer.parseInt(matcher.group(8)); } cal.set(year, month, day, hour, minute, second); cal.set(GregorianCalendar.MILLISECOND, millis); String tzString = matcher.group(9); if (tzString != null) { // timezone matched tzString = "GMT" + tzString.replace(":", ""); cal.setTimeZone(TimeZone.getTimeZone(tzString)); } else { cal.setTimeZone(TimeZone.getTimeZone("GMT")); } return cal.getTime(); } else { return null; } } }