1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| public class ISO8601Format {
public static int ZONE_INDEX = "yyyy-MM-ddTHH:mm:ss".length();
public static String DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";
public static String DATETIMEZONE_FORMAT = DATETIME_FORMAT + 'z';
public static int ZONE_HOURS_LENGTH = "+00".length();
public static int ZONE_MINUTES_INDEX = "+00:".length();
public static int ZONE_LENGTH = "+00:00".length();
public static Date parse(String date) throws ParseException {
if(date.length() <= ZONE_INDEX) {
return new SimpleDateFormat(DATETIME_FORMAT).parse(date);
} else {
String dateTimePart = date.substring(0, ZONE_INDEX);
String zonePart = date.substring(ZONE_INDEX);
if(zonePart.equals("Z")) {
date = dateTimePart + "+0000";
} else {
if(zonePart.length() != ZONE_LENGTH) {
throw new ParseException("Bad date format: " + date, ZONE_INDEX);
}
String zoneHours = zonePart.substring(0, ZONE_HOURS_LENGTH);
String zoneMinutes = zonePart.substring(ZONE_MINUTES_INDEX);
date = dateTimePart + zoneHours + zoneMinutes;
}
return new SimpleDateFormat(DATETIMEZONE_FORMAT).parse(date);
}
}
} |
Partager