add --shared
[pylucene.git] / lucene-java-3.4.0 / lucene / src / java / org / apache / lucene / document / DateTools.java
1 package org.apache.lucene.document;
2
3 /**
4  * Licensed to the Apache Software Foundation (ASF) under one or more
5  * contributor license agreements.  See the NOTICE file distributed with
6  * this work for additional information regarding copyright ownership.
7  * The ASF licenses this file to You under the Apache License, Version 2.0
8  * (the "License"); you may not use this file except in compliance with
9  * the License.  You may obtain a copy of the License at
10  *
11  *     http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19
20 import org.apache.lucene.search.NumericRangeQuery; // for javadocs
21 import org.apache.lucene.util.NumericUtils;        // for javadocs
22
23 import java.text.ParseException;
24 import java.text.SimpleDateFormat;
25 import java.util.Calendar;
26 import java.util.Date;
27 import java.util.Locale;
28 import java.util.TimeZone;
29
30 /**
31  * Provides support for converting dates to strings and vice-versa.
32  * The strings are structured so that lexicographic sorting orders 
33  * them by date, which makes them suitable for use as field values 
34  * and search terms.
35  * 
36  * <P>This class also helps you to limit the resolution of your dates. Do not
37  * save dates with a finer resolution than you really need, as then
38  * RangeQuery and PrefixQuery will require more memory and become slower.
39  * 
40  * <P>Compared to {@link DateField} the strings generated by the methods
41  * in this class take slightly more space, unless your selected resolution
42  * is set to <code>Resolution.DAY</code> or lower.
43  *
44  * <P>
45  * Another approach is {@link NumericUtils}, which provides
46  * a sortable binary representation (prefix encoded) of numeric values, which
47  * date/time are.
48  * For indexing a {@link Date} or {@link Calendar}, just get the unix timestamp as
49  * <code>long</code> using {@link Date#getTime} or {@link Calendar#getTimeInMillis} and
50  * index this as a numeric value with {@link NumericField}
51  * and use {@link NumericRangeQuery} to query it.
52  */
53 public class DateTools {
54   
55   final static TimeZone GMT = TimeZone.getTimeZone("GMT");
56
57   private static final ThreadLocal<Calendar> TL_CAL = new ThreadLocal<Calendar>() {
58     @Override
59     protected Calendar initialValue() {
60       return Calendar.getInstance(GMT, Locale.US);
61     }
62   };
63
64   //indexed by format length
65   private static final ThreadLocal<SimpleDateFormat[]> TL_FORMATS = new ThreadLocal<SimpleDateFormat[]>() {
66     @Override
67     protected SimpleDateFormat[] initialValue() {
68       SimpleDateFormat[] arr = new SimpleDateFormat[Resolution.MILLISECOND.formatLen+1];
69       for (Resolution resolution : Resolution.values()) {
70         arr[resolution.formatLen] = (SimpleDateFormat)resolution.format.clone();
71       }
72       return arr;
73     }
74   };
75
76   // cannot create, the class has static methods only
77   private DateTools() {}
78
79   /**
80    * Converts a Date to a string suitable for indexing.
81    * 
82    * @param date the date to be converted
83    * @param resolution the desired resolution, see
84    *  {@link #round(Date, DateTools.Resolution)}
85    * @return a string in format <code>yyyyMMddHHmmssSSS</code> or shorter,
86    *  depending on <code>resolution</code>; using GMT as timezone 
87    */
88   public static String dateToString(Date date, Resolution resolution) {
89     return timeToString(date.getTime(), resolution);
90   }
91
92   /**
93    * Converts a millisecond time to a string suitable for indexing.
94    * 
95    * @param time the date expressed as milliseconds since January 1, 1970, 00:00:00 GMT
96    * @param resolution the desired resolution, see
97    *  {@link #round(long, DateTools.Resolution)}
98    * @return a string in format <code>yyyyMMddHHmmssSSS</code> or shorter,
99    *  depending on <code>resolution</code>; using GMT as timezone
100    */
101   public static String timeToString(long time, Resolution resolution) {
102     final Date date = new Date(round(time, resolution));
103     return TL_FORMATS.get()[resolution.formatLen].format(date);
104   }
105   
106   /**
107    * Converts a string produced by <code>timeToString</code> or
108    * <code>dateToString</code> back to a time, represented as the
109    * number of milliseconds since January 1, 1970, 00:00:00 GMT.
110    * 
111    * @param dateString the date string to be converted
112    * @return the number of milliseconds since January 1, 1970, 00:00:00 GMT
113    * @throws ParseException if <code>dateString</code> is not in the 
114    *  expected format 
115    */
116   public static long stringToTime(String dateString) throws ParseException {
117     return stringToDate(dateString).getTime();
118   }
119
120   /**
121    * Converts a string produced by <code>timeToString</code> or
122    * <code>dateToString</code> back to a time, represented as a
123    * Date object.
124    * 
125    * @param dateString the date string to be converted
126    * @return the parsed time as a Date object 
127    * @throws ParseException if <code>dateString</code> is not in the 
128    *  expected format 
129    */
130   public static Date stringToDate(String dateString) throws ParseException {
131     try {
132       return TL_FORMATS.get()[dateString.length()].parse(dateString);
133     } catch (Exception e) {
134       throw new ParseException("Input is not a valid date string: " + dateString, 0);
135     }
136   }
137   
138   /**
139    * Limit a date's resolution. For example, the date <code>2004-09-21 13:50:11</code>
140    * will be changed to <code>2004-09-01 00:00:00</code> when using
141    * <code>Resolution.MONTH</code>. 
142    * 
143    * @param resolution The desired resolution of the date to be returned
144    * @return the date with all values more precise than <code>resolution</code>
145    *  set to 0 or 1
146    */
147   public static Date round(Date date, Resolution resolution) {
148     return new Date(round(date.getTime(), resolution));
149   }
150   
151   /**
152    * Limit a date's resolution. For example, the date <code>1095767411000</code>
153    * (which represents 2004-09-21 13:50:11) will be changed to 
154    * <code>1093989600000</code> (2004-09-01 00:00:00) when using
155    * <code>Resolution.MONTH</code>.
156    * 
157    * @param resolution The desired resolution of the date to be returned
158    * @return the date with all values more precise than <code>resolution</code>
159    *  set to 0 or 1, expressed as milliseconds since January 1, 1970, 00:00:00 GMT
160    */
161   @SuppressWarnings("fallthrough")
162   public static long round(long time, Resolution resolution) {
163     final Calendar calInstance = TL_CAL.get();
164     calInstance.setTimeInMillis(time);
165     
166     switch (resolution) {
167       //NOTE: switch statement fall-through is deliberate
168       case YEAR:
169         calInstance.set(Calendar.MONTH, 0);
170       case MONTH:
171         calInstance.set(Calendar.DAY_OF_MONTH, 1);
172       case DAY:
173         calInstance.set(Calendar.HOUR_OF_DAY, 0);
174       case HOUR:
175         calInstance.set(Calendar.MINUTE, 0);
176       case MINUTE:
177         calInstance.set(Calendar.SECOND, 0);
178       case SECOND:
179         calInstance.set(Calendar.MILLISECOND, 0);
180       case MILLISECOND:
181         // don't cut off anything
182         break;
183       default:
184         throw new IllegalArgumentException("unknown resolution " + resolution);
185     }
186     return calInstance.getTimeInMillis();
187   }
188
189   /** Specifies the time granularity. */
190   public static enum Resolution {
191     
192     YEAR(4), MONTH(6), DAY(8), HOUR(10), MINUTE(12), SECOND(14), MILLISECOND(17);
193
194     final int formatLen;
195     final SimpleDateFormat format;//should be cloned before use, since it's not threadsafe
196
197     Resolution(int formatLen) {
198       this.formatLen = formatLen;
199       // formatLen 10's place:                     11111111
200       // formatLen  1's place:            12345678901234567
201       this.format = new SimpleDateFormat("yyyyMMddHHmmssSSS".substring(0,formatLen),Locale.US);
202       this.format.setTimeZone(GMT);
203     }
204
205     /** this method returns the name of the resolution
206      * in lowercase (for backwards compatibility) */
207     @Override
208     public String toString() {
209       return super.toString().toLowerCase(Locale.ENGLISH);
210     }
211
212   }
213
214 }