pylucene 3.5.0-3
[pylucene.git] / lucene-java-3.5.0 / lucene / contrib / queryparser / src / java / org / apache / lucene / queryParser / standard / config / NumberDateFormat.java
1 package org.apache.lucene.queryParser.standard.config;
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 java.text.DateFormat;
21 import java.text.FieldPosition;
22 import java.text.Format;
23 import java.text.NumberFormat;
24 import java.text.ParsePosition;
25 import java.util.Date;
26
27 /**
28  * This {@link Format} parses {@link Long} into date strings and vice-versa. It
29  * uses the given {@link DateFormat} to parse and format dates, but before, it
30  * converts {@link Long} to {@link Date} objects or vice-versa.
31  */
32 public class NumberDateFormat extends NumberFormat {
33   
34   private static final long serialVersionUID = 964823936071308283L;
35   
36   final private DateFormat dateFormat;
37   
38   /**
39    * Constructs a {@link NumberDateFormat} object using the given {@link DateFormat}.
40    * 
41    * @param dateFormat {@link DateFormat} used to parse and format dates
42    */
43   public NumberDateFormat(DateFormat dateFormat) {
44     this.dateFormat = dateFormat;
45   }
46   
47   @Override
48   public StringBuffer format(double number, StringBuffer toAppendTo,
49       FieldPosition pos) {
50     return dateFormat.format(new Date((long) number), toAppendTo, pos);
51   }
52   
53   @Override
54   public StringBuffer format(long number, StringBuffer toAppendTo,
55       FieldPosition pos) {
56     return dateFormat.format(new Date(number), toAppendTo, pos);
57   }
58   
59   @Override
60   public Number parse(String source, ParsePosition parsePosition) {
61     final Date date = dateFormat.parse(source, parsePosition);
62     return (date == null) ? null : date.getTime();
63   }
64   
65   @Override
66   public StringBuffer format(Object number, StringBuffer toAppendTo,
67       FieldPosition pos) {
68     return dateFormat.format(number, toAppendTo, pos);
69   }
70   
71 }