KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > alfresco > util > ISO8601DateFormat


1 /*
2  * Copyright (C) 2005 Alfresco, Inc.
3  *
4  * Licensed under the Mozilla Public License version 1.1
5  * with a permitted attribution clause. You may obtain a
6  * copy of the License at
7  *
8  * http://www.alfresco.org/legal/license.txt
9  *
10  * Unless required by applicable law or agreed to in writing,
11  * software distributed under the License is distributed on an
12  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13  * either express or implied. See the License for the specific
14  * language governing permissions and limitations under the
15  * License.
16  */

17 package org.alfresco.util;
18
19 import java.util.Calendar JavaDoc;
20 import java.util.Date JavaDoc;
21 import java.util.GregorianCalendar JavaDoc;
22 import java.util.TimeZone JavaDoc;
23
24
25 /**
26  * Formatting support for ISO 8601 dates
27  * <pre>
28  * sYYYY-MM-DDThh:mm:ss.sssTZD
29  * </pre>
30  * where:
31  * <ul>
32  * <li>sYYYY Four-digit year with optional leading positive (<b>+</b>) or negative (<b>-</b>) sign.
33  * A negative sign indicates a year BCE. The absence of a sign or the presence of a
34  * positive sign indicates a year CE (for example, -0055 would indicate the year 55 BCE,
35  * while +1969 and 1969 indicate the year 1969 CE).</li>
36  * <li>MM Two-digit month (01 = January, etc.)</li>
37  * <li>DD Two-digit day of month (01 through 31)</li>
38  * <li>hh Two digits of hour (00 through 23)</li>
39  * <li>mm Two digits of minute (00 through 59)</li>
40  * <li>ss.sss Seconds, to three decimal places (00.000 through 59.999)</li>
41  * <li>TZD Time zone designator (either Z for Zulu, i.e. UTC, or +hh:mm or -hh:mm, i.e. an offset from UTC)</li>
42  * </ul>
43  */

44 public class ISO8601DateFormat
45 {
46     
47     /**
48      * Format date into ISO format
49      *
50      * @param isoDate the date to format
51      * @return the ISO formatted string
52      */

53     public static String JavaDoc format(Date JavaDoc isoDate)
54     {
55         Calendar JavaDoc calendar = new GregorianCalendar JavaDoc();
56         calendar.setTime(isoDate);
57         
58         StringBuffer JavaDoc formatted = new StringBuffer JavaDoc();
59         padInt(formatted, calendar.get(Calendar.YEAR), 4);
60         formatted.append('-');
61         padInt(formatted, calendar.get(Calendar.MONTH) + 1, 2);
62         formatted.append('-');
63         padInt(formatted, calendar.get(Calendar.DAY_OF_MONTH), 2);
64         formatted.append('T');
65         padInt(formatted, calendar.get(Calendar.HOUR_OF_DAY), 2);
66         formatted.append(':');
67         padInt(formatted, calendar.get(Calendar.MINUTE), 2);
68         formatted.append(':');
69         padInt(formatted, calendar.get(Calendar.SECOND), 2);
70         formatted.append('.');
71         padInt(formatted, calendar.get(Calendar.MILLISECOND), 3);
72
73         TimeZone JavaDoc tz = calendar.getTimeZone();
74         int offset = tz.getOffset(calendar.getTimeInMillis());
75         if (offset != 0)
76         {
77             int hours = Math.abs((offset / (60 * 1000)) / 60);
78             int minutes = Math.abs((offset / (60 * 1000)) % 60);
79             formatted.append(offset < 0 ? '-' : '+');
80             padInt(formatted, hours, 2);
81             formatted.append(':');
82             padInt(formatted, minutes, 2);
83         }
84         else
85         {
86             formatted.append('Z');
87         }
88         
89         return formatted.toString();
90     }
91     
92     
93     /**
94      * Parse date from ISO formatted string
95      *
96      * @param isoDate ISO string to parse
97      * @return the date
98      */

99     public static Date JavaDoc parse(String JavaDoc isoDate)
100     {
101         Date JavaDoc parsed = null;
102         
103         try
104         {
105             int offset = 0;
106         
107             // extract year
108
int year = Integer.parseInt(isoDate.substring(offset, offset += 4));
109             if (isoDate.charAt(offset) != '-')
110             {
111                 throw new IndexOutOfBoundsException JavaDoc("Expected - character but found " + isoDate.charAt(offset));
112             }
113             
114             // extract month
115
int month = Integer.parseInt(isoDate.substring(offset += 1, offset += 2));
116             if (isoDate.charAt(offset) != '-')
117             {
118                 throw new IndexOutOfBoundsException JavaDoc("Expected - character but found " + isoDate.charAt(offset));
119             }
120
121             // extract day
122
int day = Integer.parseInt(isoDate.substring(offset += 1, offset += 2));
123             if (isoDate.charAt(offset) != 'T')
124             {
125                 throw new IndexOutOfBoundsException JavaDoc("Expected T character but found " + isoDate.charAt(offset));
126             }
127
128             // extract hours, minutes, seconds and milliseconds
129
int hour = Integer.parseInt(isoDate.substring(offset += 1, offset += 2));
130             if (isoDate.charAt(offset) != ':')
131             {
132                 throw new IndexOutOfBoundsException JavaDoc("Expected T character but found " + isoDate.charAt(offset));
133             }
134             int minutes = Integer.parseInt(isoDate.substring(offset += 1, offset += 2));
135             if (isoDate.charAt(offset) != ':')
136             {
137                 throw new IndexOutOfBoundsException JavaDoc("Expected : character but found " + isoDate.charAt(offset));
138             }
139             int seconds = Integer.parseInt(isoDate.substring(offset += 1 , offset += 2));
140             if (isoDate.charAt(offset) != '.')
141             {
142                 throw new IndexOutOfBoundsException JavaDoc("Expected . character but found " + isoDate.charAt(offset));
143             }
144             int milliseconds = Integer.parseInt(isoDate.substring(offset += 1, offset += 3));
145
146             // extract timezone
147
String JavaDoc timezoneId;
148             char timezoneIndicator = isoDate.charAt(offset);
149             if (timezoneIndicator == '+' || timezoneIndicator == '-')
150             {
151                 timezoneId = "GMT" + isoDate.substring(offset);
152             }
153             else if (timezoneIndicator == 'Z')
154             {
155                 timezoneId = "GMT";
156             }
157             else
158             {
159                 throw new IndexOutOfBoundsException JavaDoc("Invalid time zone indicator " + timezoneIndicator);
160             }
161             TimeZone JavaDoc timezone = TimeZone.getTimeZone(timezoneId);
162             if (!timezone.getID().equals(timezoneId))
163             {
164                 throw new IndexOutOfBoundsException JavaDoc();
165             }
166
167             // initialize Calendar object
168
Calendar JavaDoc calendar = Calendar.getInstance(timezone);
169             calendar.setLenient(false);
170             calendar.set(Calendar.YEAR, year);
171             calendar.set(Calendar.MONTH, month - 1);
172             calendar.set(Calendar.DAY_OF_MONTH, day);
173             calendar.set(Calendar.HOUR_OF_DAY, hour);
174             calendar.set(Calendar.MINUTE, minutes);
175             calendar.set(Calendar.SECOND, seconds);
176             calendar.set(Calendar.MILLISECOND, milliseconds);
177
178             // extract the date
179
parsed = calendar.getTime();
180         }
181         catch(IndexOutOfBoundsException JavaDoc e)
182         {
183         }
184         catch(NumberFormatException JavaDoc e)
185         {
186         }
187         catch(IllegalArgumentException JavaDoc e)
188         {
189         }
190         
191         return parsed;
192     }
193     
194     /**
195      * Helper to zero pad a number to specified length
196      */

197     private static void padInt(StringBuffer JavaDoc buffer, int value, int length)
198     {
199         String JavaDoc strValue = Integer.toString(value);
200         for (int i = length - strValue.length(); i > 0; i--)
201         {
202             buffer.append('0');
203         }
204         buffer.append(strValue);
205     }
206     
207 }
208
Popular Tags