001/* 002 * (C) Copyright 2006-2012 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Nuxeo - initial API and implementation 018 */ 019package org.nuxeo.ecm.core.schema.utils; 020 021import java.text.ParseException; 022import java.util.Calendar; 023import java.util.Date; 024import java.util.GregorianCalendar; 025import java.util.TimeZone; 026 027/** 028 * Parse / format ISO 8601 dates. 029 * 030 * @author "Stephane Lacoin [aka matic] <slacoin at nuxeo.com>" 031 */ 032public class DateParser { 033 034 public static Calendar parse(String str) throws ParseException { 035 if (str == null) { 036 return null; 037 } 038 Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("UTC")); 039 cal.clear(); 040 int len = str.length(); 041 if (len == 0) { // empty string 042 // TODO throw error? 043 return cal; 044 } 045 int i = 0; 046 i = readYear(cal, str, i); 047 i = readCharOpt('-', cal, str, i); 048 if (i == -1) { 049 return cal; 050 } 051 i = readMonth(cal, str, i); 052 i = readCharOpt('-', cal, str, i); 053 if (i == -1) { 054 return cal; 055 } 056 i = readDay(cal, str, i); 057 i = readCharOpt('T', cal, str, i); 058 if (i == -1) { 059 return cal; 060 } 061 i = readHours(cal, str, i); 062 i = readCharOpt(':', cal, str, i); 063 if (i == -1) { 064 return cal; 065 } 066 i = readMinutes(cal, str, i); 067 if (isChar(':', str, i)) { 068 i = readSeconds(cal, str, i + 1); 069 if (isChar('.', str, i)) { 070 i = readMilliseconds(cal, str, i + 1); 071 } 072 } 073 if (i > -1) { 074 readTimeZone(cal, str, i); 075 } 076 return cal; 077 } 078 079 public static Date parseW3CDateTime(String str) { 080 if (str == null || "".equals(str)) { 081 return null; 082 } 083 try { 084 return parse(str).getTime(); 085 } catch (ParseException e) { 086 throw new IllegalArgumentException("Failed to parse ISO 8601 date: " + str, e); 087 } 088 } 089 090 /** 091 * 2011-10-23T12:00:00.00Z 092 * 093 * @param date 094 * @return 095 */ 096 public static String formatW3CDateTime(Date date) { 097 if (date == null) { 098 return null; 099 } 100 Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("UTC")); 101 cal.setTime(date); 102 StringBuilder buf = new StringBuilder(32); 103 return buf.append(cal.get(Calendar.YEAR)).append('-').append(pad(cal.get(Calendar.MONTH) + 1)).append('-').append( 104 pad(cal.get(Calendar.DATE))).append('T').append(pad(cal.get(Calendar.HOUR_OF_DAY))).append(':').append( 105 pad(cal.get(Calendar.MINUTE))).append(':').append(pad(cal.get(Calendar.SECOND))).append('.').append( 106 pad(cal.get(Calendar.MILLISECOND) / 10)).append('Z').toString(); 107 } 108 109 /** 110 * 2011-10-23T12:00:00.00Z 111 * 112 * @param calendar 113 * @return 114 * 115 * @since 7.3 116 */ 117 public static String formatW3CDateTime(Calendar calendar) { 118 if (calendar == null) { 119 return null; 120 } 121 return formatW3CDateTime(calendar.getTime()); 122 } 123 124 private final static String pad(int i) { 125 return i < 10 ? "0".concat(String.valueOf(i)) : String.valueOf(i); 126 } 127 128 private final static int readYear(Calendar cal, String str, int off) throws ParseException { 129 if (str.length() >= off + 4) { 130 cal.set(Calendar.YEAR, Integer.parseInt(str.substring(off, off + 4))); 131 return off + 4; 132 } 133 throw new ParseException("Invalid year in date '" + str + "'", off); 134 } 135 136 private final static int readMonth(Calendar cal, String str, int off) throws ParseException { 137 if (str.length() >= off + 2) { 138 cal.set(Calendar.MONTH, Integer.parseInt(str.substring(off, off + 2)) - 1); 139 return off + 2; 140 } 141 throw new ParseException("Invalid month in date '" + str + "'", off); 142 } 143 144 private final static int readDay(Calendar cal, String str, int off) throws ParseException { 145 if (str.length() >= off + 2) { 146 cal.set(Calendar.DATE, Integer.parseInt(str.substring(off, off + 2))); 147 return off + 2; 148 } 149 throw new ParseException("Invalid day in date '" + str + "'", off); 150 } 151 152 private final static int readHours(Calendar cal, String str, int off) throws ParseException { 153 if (str.length() >= off + 2) { 154 cal.set(Calendar.HOUR, Integer.parseInt(str.substring(off, off + 2))); 155 return off + 2; 156 } 157 throw new ParseException("Invalid hours in date '" + str + "'", off); 158 } 159 160 private final static int readMinutes(Calendar cal, String str, int off) throws ParseException { 161 if (str.length() >= off + 2) { 162 cal.set(Calendar.MINUTE, Integer.parseInt(str.substring(off, off + 2))); 163 return off + 2; 164 } 165 throw new ParseException("Invalid minutes in date '" + str + "'", off); 166 } 167 168 private final static int readSeconds(Calendar cal, String str, int off) throws ParseException { 169 if (str.length() >= off + 2) { 170 cal.set(Calendar.SECOND, Integer.parseInt(str.substring(off, off + 2))); 171 return off + 2; 172 } 173 throw new ParseException("Invalid seconds in date '" + str + "'", off); 174 } 175 176 /** 177 * Return -1 if no more content to read or the offset of the expected TZ 178 * 179 * @param cal 180 * @param str 181 * @param off 182 * @return 183 * @throws ParseException 184 */ 185 private final static int readMilliseconds(Calendar cal, String str, int off) throws ParseException { 186 int e = str.indexOf('Z', off); 187 if (e == -1) { 188 e = str.indexOf('+', off); 189 if (e == -1) { 190 e = str.indexOf('-', off); 191 } 192 } 193 String ms = e == -1 ? str.substring(off) : str.substring(off, e); 194 // need to normalize the ms fraction to 3 digits. 195 // If less than 3 digits right pad with 0 196 // If more than 3 digits truncate to 3 digits. 197 int mslen = ms.length(); 198 if (mslen > 0) { 199 int f = 0; 200 switch (mslen) { 201 case 1: 202 f = Integer.parseInt(ms) * 100; 203 break; 204 case 2: 205 f = Integer.parseInt(ms) * 10; 206 break; 207 case 3: 208 f = Integer.parseInt(ms); 209 break; 210 default: // truncate 211 f = Integer.parseInt(ms.substring(0, 3)); 212 break; 213 } 214 cal.set(Calendar.MILLISECOND, f); 215 } 216 return e; 217 } 218 219 private static final boolean isChar(char c, String str, int off) { 220 return str.length() > off && str.charAt(off) == c; 221 } 222 223 private static final int readCharOpt(char c, Calendar cal, String str, int off) { 224 if (str.length() > off) { 225 if (str.charAt(off) == c) { 226 return off + 1; 227 } 228 } 229 return -1; 230 } 231 232 private final static boolean readTimeZone(Calendar cal, String str, int off) throws ParseException { 233 int len = str.length(); 234 if (len == off) { 235 return false; 236 } 237 char c = str.charAt(off); 238 if (c == 'Z') { 239 return true; 240 } 241 off++; 242 boolean plus = false; 243 if (c == '+') { 244 plus = true; 245 } else if (c != '-') { 246 throw new ParseException("Only Z, +, - prefixes are allowed in TZ", off); 247 } 248 int h = 0; 249 int m = 0; 250 int d = len - off; 251 /** 252 * We check here the different format of timezone * +02 (d=2 : doesn't seem to be in ISO-8601 but left for 253 * compat) * +02:00 (d=5) * +0200 (d=4) 254 */ 255 if (d == 2) { 256 h = Integer.parseInt(str.substring(off, off + 2)); 257 } else if (d == 5) { 258 h = Integer.parseInt(str.substring(off, off + 2)); 259 m = Integer.parseInt(str.substring(off + 3, off + 5)); 260 // we do not check for ':'. we assume it is in the correct format 261 } else if (d == 4) { 262 h = Integer.parseInt(str.substring(off, off + 2)); 263 m = Integer.parseInt(str.substring(off + 2, off + 4)); 264 } else { 265 throw new ParseException("Invalid TZ in \"" + str + "\"", off); 266 } 267 268 if (plus) { 269 cal.add(Calendar.HOUR, -h); 270 cal.add(Calendar.MINUTE, -m); 271 } else { 272 cal.add(Calendar.HOUR, h); 273 cal.add(Calendar.MINUTE, m); 274 } 275 276 return true; 277 } 278 279}