1 package org.apache.lucene.document;
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 import org.apache.lucene.search.NumericRangeQuery; // for javadocs
21 import org.apache.lucene.util.NumericUtils; // for javadocs
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;
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
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.
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.
45 * Another approach is {@link NumericUtils}, which provides
46 * a sortable binary representation (prefix encoded) of numeric values, which
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.
53 public class DateTools {
55 final static TimeZone GMT = TimeZone.getTimeZone("GMT");
57 private static final ThreadLocal<Calendar> TL_CAL = new ThreadLocal<Calendar>() {
59 protected Calendar initialValue() {
60 return Calendar.getInstance(GMT, Locale.US);
64 //indexed by format length
65 private static final ThreadLocal<SimpleDateFormat[]> TL_FORMATS = new ThreadLocal<SimpleDateFormat[]>() {
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();
76 // cannot create, the class has static methods only
77 private DateTools() {}
80 * Converts a Date to a string suitable for indexing.
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
88 public static String dateToString(Date date, Resolution resolution) {
89 return timeToString(date.getTime(), resolution);
93 * Converts a millisecond time to a string suitable for indexing.
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
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);
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.
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
116 public static long stringToTime(String dateString) throws ParseException {
117 return stringToDate(dateString).getTime();
121 * Converts a string produced by <code>timeToString</code> or
122 * <code>dateToString</code> back to a time, represented as a
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
130 public static Date stringToDate(String dateString) throws ParseException {
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);
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>.
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>
147 public static Date round(Date date, Resolution resolution) {
148 return new Date(round(date.getTime(), resolution));
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>.
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
161 @SuppressWarnings("fallthrough")
162 public static long round(long time, Resolution resolution) {
163 final Calendar calInstance = TL_CAL.get();
164 calInstance.setTimeInMillis(time);
166 switch (resolution) {
167 //NOTE: switch statement fall-through is deliberate
169 calInstance.set(Calendar.MONTH, 0);
171 calInstance.set(Calendar.DAY_OF_MONTH, 1);
173 calInstance.set(Calendar.HOUR_OF_DAY, 0);
175 calInstance.set(Calendar.MINUTE, 0);
177 calInstance.set(Calendar.SECOND, 0);
179 calInstance.set(Calendar.MILLISECOND, 0);
181 // don't cut off anything
184 throw new IllegalArgumentException("unknown resolution " + resolution);
186 return calInstance.getTimeInMillis();
189 /** Specifies the time granularity. */
190 public static enum Resolution {
192 YEAR(4), MONTH(6), DAY(8), HOUR(10), MINUTE(12), SECOND(14), MILLISECOND(17);
195 final SimpleDateFormat format;//should be cloned before use, since it's not threadsafe
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);
205 /** this method returns the name of the resolution
206 * in lowercase (for backwards compatibility) */
208 public String toString() {
209 return super.toString().toLowerCase(Locale.ENGLISH);