KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > pdfbox > util > DateConverter


1 /**
2  * Copyright (c) 2003-2006, www.pdfbox.org
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright notice,
9  * this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright notice,
11  * this list of conditions and the following disclaimer in the documentation
12  * and/or other materials provided with the distribution.
13  * 3. Neither the name of pdfbox; nor the names of its
14  * contributors may be used to endorse or promote products derived from this
15  * software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20  * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
21  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
24  * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  *
28  * http://www.pdfbox.org
29  *
30  */

31 package org.pdfbox.util;
32
33 import java.text.ParseException JavaDoc;
34 import java.text.SimpleDateFormat JavaDoc;
35
36 import java.io.IOException JavaDoc;
37
38 import java.util.Calendar JavaDoc;
39 import java.util.Date JavaDoc;
40 import java.util.GregorianCalendar JavaDoc;
41 import java.util.SimpleTimeZone JavaDoc;
42 import java.util.TimeZone JavaDoc;
43
44 import org.pdfbox.cos.COSString;
45
46 /**
47  * This class is used to convert dates to strings and back using the PDF
48  * date standards. Date are described in PDFReference1.4 section 3.8.2
49  *
50  * @author <a HREF="mailto:ben@benlitchfield.com">Ben Litchfield</a>
51  * @version $Revision: 1.13 $
52  */

53 public class DateConverter
54 {
55     private static final SimpleDateFormat JavaDoc PDF_DATE_FORMAT = new SimpleDateFormat JavaDoc( "yyyyMMddHHmmss" );
56     
57     //The Date format is supposed to be the PDF_DATE_FORMAT, but not all PDF documents
58
//will use that date, so I have added a couple other potential formats
59
//to try if the original one does not work.
60
private static final SimpleDateFormat JavaDoc[] POTENTIAL_FORMATS = new SimpleDateFormat JavaDoc[] {
61         new SimpleDateFormat JavaDoc("EEEE, dd MMM yyyy hh:mm:ss a"),
62         new SimpleDateFormat JavaDoc("EEEE, MMM dd, yyyy hh:mm:ss a"),
63         new SimpleDateFormat JavaDoc("MM/dd/yyyy hh:mm:ss"),
64         new SimpleDateFormat JavaDoc("MM/dd/yyyy")};
65     
66     private static final SimpleDateFormat JavaDoc ISO_8601_DATE_FORMAT = new SimpleDateFormat JavaDoc( "yyyy-MM-dd'T'HH:mm:ss" );
67     
68     private DateConverter()
69     {
70         //utility class should not be constructed.
71
}
72
73     /**
74      * This will convert the calendar to a string.
75      *
76      * @param date The date to convert to a string.
77      *
78      * @return The date as a String to be used in a PDF document.
79      */

80     public static String JavaDoc toString( Calendar JavaDoc date )
81     {
82         String JavaDoc retval = null;
83         if( date != null )
84         {
85             StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
86             TimeZone JavaDoc zone = date.getTimeZone();
87             long offsetInMinutes = zone.getOffset( date.getTimeInMillis() )/1000/60;
88             long hours = Math.abs( offsetInMinutes/60 );
89             long minutes = Math.abs( offsetInMinutes%60 );
90             buffer.append( "D:" );
91             buffer.append( PDF_DATE_FORMAT.format( date.getTime() ) );
92             if( offsetInMinutes == 0 )
93             {
94                 buffer.append( "Z" );
95             }
96             else if( offsetInMinutes < 0 )
97             {
98                 buffer.append( "-" );
99             }
100             else
101             {
102                 buffer.append( "+" );
103             }
104             if( hours < 10 )
105             {
106                 buffer.append( "0" );
107             }
108             buffer.append( hours );
109             buffer.append( "'" );
110             if( minutes < 10 )
111             {
112                 buffer.append( "0" );
113             }
114             buffer.append( minutes );
115             buffer.append( "'" );
116             retval = buffer.toString();
117             
118         }
119         return retval;
120     }
121     
122     /**
123      * This will convert a string to a calendar.
124      *
125      * @param date The string representation of the calendar.
126      *
127      * @return The calendar that this string represents.
128      *
129      * @throws IOException If the date string is not in the correct format.
130      */

131     public static Calendar JavaDoc toCalendar( COSString date ) throws IOException JavaDoc
132     {
133         Calendar JavaDoc retval = null;
134         if( date != null )
135         {
136             retval = toCalendar( date.getString() );
137         }
138         
139         return retval;
140     }
141
142     /**
143      * This will convert a string to a calendar.
144      *
145      * @param date The string representation of the calendar.
146      *
147      * @return The calendar that this string represents.
148      *
149      * @throws IOException If the date string is not in the correct format.
150      */

151     public static Calendar JavaDoc toCalendar( String JavaDoc date ) throws IOException JavaDoc
152     {
153         Calendar JavaDoc retval = null;
154         if( date != null && date.trim().length() > 0 )
155         {
156             //these are the default values
157
int year = 0;
158             int month = 1;
159             int day = 1;
160             int hour = 0;
161             int minute = 0;
162             int second = 0;
163             //first string off the prefix if it exists
164
try
165             {
166                 SimpleTimeZone JavaDoc zone = null;
167                 if( date.startsWith( "D:" ) )
168                 {
169                     date = date.substring( 2, date.length() );
170                 }
171                 if( date.length() < 4 )
172                 {
173                     throw new IOException JavaDoc( "Error: Invalid date format '" + date + "'" );
174                 }
175                 year = Integer.parseInt( date.substring( 0, 4 ) );
176                 if( date.length() >= 6 )
177                 {
178                     month = Integer.parseInt( date.substring( 4, 6 ) );
179                 }
180                 if( date.length() >= 8 )
181                 {
182                     day = Integer.parseInt( date.substring( 6, 8 ) );
183                 }
184                 if( date.length() >= 10 )
185                 {
186                     hour = Integer.parseInt( date.substring( 8, 10 ) );
187                 }
188                 if( date.length() >= 12 )
189                 {
190                     minute = Integer.parseInt( date.substring( 10, 12 ) );
191                 }
192                 if( date.length() >= 14 )
193                 {
194                     second = Integer.parseInt( date.substring( 12, 14 ) );
195                 }
196                 retval = new GregorianCalendar JavaDoc( year, month-1, day, hour, minute, second );
197                 if( date.length() >= 15 )
198                 {
199                     char sign = date.charAt( 14 );
200                     if( sign == 'Z' )
201                     {
202                         zone = new SimpleTimeZone JavaDoc(0,"Unknown");
203                     }
204                     else
205                     {
206                         int hours = 0;
207                         int minutes = 0;
208                         if( date.length() >= 17 )
209                         {
210                             if( sign == '+' )
211                             {
212                                 //parseInt cannot handle the + sign
213
hours = Integer.parseInt( date.substring( 15, 17 ) );
214                             }
215                             else
216                             {
217                                 hours = Integer.parseInt( date.substring( 14, 17 ) );
218                             }
219                         }
220                         if( date.length() > 20 )
221                         {
222                             minutes = Integer.parseInt( date.substring( 18, 20 ) );
223                         }
224                         zone = new SimpleTimeZone JavaDoc( hours*60*60*1000 + minutes*60*1000, "Unknown" );
225                     }
226                     retval.setTimeZone( zone );
227                 }
228             }
229             catch( NumberFormatException JavaDoc e )
230             {
231                 for( int i=0; retval == null && i<POTENTIAL_FORMATS.length; i++ )
232                 {
233                     try
234                     {
235                         Date JavaDoc utilDate = POTENTIAL_FORMATS[i].parse( date );
236                         retval = new GregorianCalendar JavaDoc();
237                         retval.setTime( utilDate );
238                     }
239                     catch( ParseException JavaDoc pe )
240                     {
241                         //ignore and move to next potential format
242
}
243                 }
244                 if( retval == null )
245                 {
246                     //we didn't find a valid date format so throw an exception
247
throw new IOException JavaDoc( "Error converting date:" + date );
248                 }
249             }
250         }
251         return retval;
252     }
253     
254     /**
255      * Convert the date to iso 8601 string format.
256      *
257      * @param cal The date to convert.
258      * @return The date represented as an ISO 8601 string.
259      */

260     public static String JavaDoc toISO8601( Calendar JavaDoc cal )
261     {
262         StringBuffer JavaDoc retval = new StringBuffer JavaDoc();
263         retval.append( ISO_8601_DATE_FORMAT.format( cal.getTime() ) );
264         int timeZone = cal.get( Calendar.ZONE_OFFSET );
265         if( timeZone < 0 )
266         {
267             retval.append( "-" );
268         }
269         else
270         {
271             retval.append( "+" );
272         }
273         timeZone = Math.abs( timeZone );
274         //milliseconds/1000 = seconds = seconds / 60 = minutes = minutes/60 = hours
275
int hours = timeZone/1000/60/60;
276         int minutes = (timeZone - (hours*1000*60*60))/1000/1000;
277         if( hours < 10 )
278         {
279             retval.append( "0" );
280         }
281         retval.append( Integer.toString( hours ) );
282         retval.append( ":" );
283         if( minutes < 10 )
284         {
285             retval.append( "0" );
286         }
287         retval.append( Integer.toString( minutes ) );
288         
289         return retval.toString();
290     }
291 }
Popular Tags