Created
May 6, 2014 17:29
-
-
Save kzim44/912066b198487c262aaa to your computer and use it in GitHub Desktop.
Class to parse ISO8601 dates for Android apps.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Helper class for handling ISO 8601 strings of the following format: | |
* "2008-03-01T13:00:00+01:00". It also supports parsing the "Z" timezone. | |
*/ | |
public final class Iso8601 { | |
/** Transform Calendar to ISO 8601 string. */ | |
public static String fromCalendar(final Calendar calendar) { | |
Date date = calendar.getTime(); | |
String formatted = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") | |
.format(date); | |
return formatted.substring(0, 22) + ":" + formatted.substring(22); | |
} | |
/** Get current date and time formatted as ISO 8601 string. */ | |
public static String now() { | |
return fromCalendar(GregorianCalendar.getInstance()); | |
} | |
/** Transform ISO 8601 string to Calendar. */ | |
public static Calendar toCalendar(final String iso8601string) | |
throws ParseException { | |
Calendar calendar = GregorianCalendar.getInstance(); | |
String s = iso8601string.replace("Z", "+00:00"); | |
try { | |
s = s.substring(0, 22) + s.substring(23); // to get rid of the ":" | |
} catch (IndexOutOfBoundsException e) { | |
throw new ParseException("Invalid length", 0); | |
} | |
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(s); | |
calendar.setTime(date); | |
return calendar; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey,
Doesn't seem correct: you get rid of the Z and you parse it?