Guest User

Untitled

a guest
May 23rd, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. /**
  2. * Helper class for handling ISO 8601 strings of the following format:
  3. * "2008-03-01T13:00:00+01:00". It also supports parsing the "Z" timezone.
  4. */
  5. public final class Iso8601 {
  6. /** Transform Calendar to ISO 8601 string. */
  7. public static String fromCalendar(final Calendar calendar) {
  8. Date date = calendar.getTime();
  9. String formatted = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
  10. .format(date);
  11. return formatted.substring(0, 22) + ":" + formatted.substring(22);
  12. }
  13.  
  14. /** Get current date and time formatted as ISO 8601 string. */
  15. public static String now() {
  16. return fromCalendar(GregorianCalendar.getInstance());
  17. }
  18.  
  19. /** Transform ISO 8601 string to Calendar. */
  20. public static Calendar toCalendar(final String iso8601string)
  21. throws ParseException {
  22. Calendar calendar = GregorianCalendar.getInstance();
  23. String s = iso8601string.replace("Z", "+00:00");
  24. try {
  25. s = s.substring(0, 22) + s.substring(23); // to get rid of the ":"
  26. } catch (IndexOutOfBoundsException e) {
  27. throw new ParseException("Invalid length", 0);
  28. }
  29. Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(s);
  30. calendar.setTime(date);
  31. return calendar;
  32. }
  33. }
Add Comment
Please, Sign In to add comment