1 24 package javax.jcr.util; 25 26 import java.text.DecimalFormat ; 27 import java.text.ParsePosition ; 28 import java.text.SimpleDateFormat ; 29 import java.util.Calendar ; 30 import java.util.Date ; 31 import java.util.TimeZone ; 32 33 46 public final class ISO8601 { 47 50 private static DecimalFormat xxFormat = new DecimalFormat ("00"); 51 52 55 private static String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS"; 56 57 64 public static Calendar parse(String text) { 65 String tzID = "GMT"; int tzPos = text.indexOf('Z'); 69 if (tzPos == -1) { 70 tzPos = text.indexOf('+'); 72 if (tzPos == -1) { 73 tzPos = text.indexOf('-', 8); 76 } 77 if (tzPos == -1) { 78 } else { 80 tzID += text.substring(tzPos); 82 text = text.substring(0, tzPos); 83 } 84 } else { 85 text = text.substring(0, tzPos); 87 } 88 89 TimeZone tz = TimeZone.getTimeZone(tzID); 90 SimpleDateFormat format = new SimpleDateFormat (ISO_FORMAT); 91 format.setLenient(false); 92 format.setTimeZone(tz); 93 Date date = format.parse(text, new ParsePosition (0)); 94 if (date == null) { 95 return null; 96 } 97 Calendar cal = Calendar.getInstance(tz); 98 cal.setTime(date); 99 return cal; 100 } 101 102 109 public static String format(Calendar cal) { 110 SimpleDateFormat format = 111 new SimpleDateFormat (ISO_FORMAT); 112 TimeZone tz = cal.getTimeZone(); 113 format.setTimeZone(tz); 114 115 StringBuffer tzd = new StringBuffer (); 116 int offset = tz.getRawOffset(); 117 if (offset != 0) { 118 int hours = Math.abs((offset / (60 * 1000)) / 60); 119 int minutes = Math.abs((offset / (60 * 1000)) % 60); 120 tzd.append(offset < 0 ? "-" : "+"); 121 tzd.append(xxFormat.format(hours)); 122 tzd.append(":"); 123 tzd.append(xxFormat.format(minutes)); 124 } else { 125 tzd.append("Z"); 126 } 127 return format.format(cal.getTime()) + tzd.toString(); 128 } 129 } 130 | Popular Tags |