PageRenderTime 19ms CodeModel.GetById 15ms app.highlight 2ms RepoModel.GetById 1ms app.codeStats 0ms

/tags/release-0.1-rc2/hive/external/ql/src/java/org/apache/hadoop/hive/ql/udf/UDFYear.java

#
Java | 75 lines | 35 code | 10 blank | 30 comment | 2 complexity | eda1b0da0254946b5dc2de9caf877dac MD5 | raw file
 1/**
 2 * Licensed to the Apache Software Foundation (ASF) under one
 3 * or more contributor license agreements.  See the NOTICE file
 4 * distributed with this work for additional information
 5 * regarding copyright ownership.  The ASF licenses this file
 6 * to you under the Apache License, Version 2.0 (the
 7 * "License"); you may not use this file except in compliance
 8 * with the License.  You may obtain a copy of the License at
 9 *
10 *     http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19package org.apache.hadoop.hive.ql.udf;
20
21import java.text.ParseException;
22import java.text.SimpleDateFormat;
23import java.util.Calendar;
24import java.util.Date;
25
26import org.apache.hadoop.hive.ql.exec.Description;
27import org.apache.hadoop.hive.ql.exec.UDF;
28import org.apache.hadoop.io.IntWritable;
29import org.apache.hadoop.io.Text;
30
31/**
32 * UDFYear.
33 *
34 */
35@Description(name = "year", 
36    value = "_FUNC_(date) - Returns the year of date", 
37    extended = "date is a string in the format of 'yyyy-MM-dd HH:mm:ss' or "
38    + "'yyyy-MM-dd'.\n"
39    + "Example:\n "
40    + "  > SELECT _FUNC_('2009-30-07', 1) FROM src LIMIT 1;\n" + "  2009")
41public class UDFYear extends UDF {
42  private final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
43  private final Calendar calendar = Calendar.getInstance();
44
45  private IntWritable result = new IntWritable();
46
47  public UDFYear() {
48  }
49
50  /**
51   * Get the year from a date string.
52   * 
53   * @param dateString
54   *          the dateString in the format of "yyyy-MM-dd HH:mm:ss" or
55   *          "yyyy-MM-dd".
56   * @return an int from 1 to 12. null if the dateString is not a valid date
57   *         string.
58   */
59  public IntWritable evaluate(Text dateString) {
60
61    if (dateString == null) {
62      return null;
63    }
64
65    try {
66      Date date = formatter.parse(dateString.toString());
67      calendar.setTime(date);
68      result.set(calendar.get(Calendar.YEAR));
69      return result;
70    } catch (ParseException e) {
71      return null;
72    }
73  }
74
75}