PageRenderTime 50ms CodeModel.GetById 4ms RepoModel.GetById 0ms app.codeStats 1ms

/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
Possible License(s): Apache-2.0, BSD-3-Clause, JSON, CPL-1.0
  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. package org.apache.hadoop.hive.ql.udf;
  19. import java.text.ParseException;
  20. import java.text.SimpleDateFormat;
  21. import java.util.Calendar;
  22. import java.util.Date;
  23. import org.apache.hadoop.hive.ql.exec.Description;
  24. import org.apache.hadoop.hive.ql.exec.UDF;
  25. import org.apache.hadoop.io.IntWritable;
  26. import org.apache.hadoop.io.Text;
  27. /**
  28. * UDFYear.
  29. *
  30. */
  31. @Description(name = "year",
  32. value = "_FUNC_(date) - Returns the year of date",
  33. extended = "date is a string in the format of 'yyyy-MM-dd HH:mm:ss' or "
  34. + "'yyyy-MM-dd'.\n"
  35. + "Example:\n "
  36. + " > SELECT _FUNC_('2009-30-07', 1) FROM src LIMIT 1;\n" + " 2009")
  37. public class UDFYear extends UDF {
  38. private final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
  39. private final Calendar calendar = Calendar.getInstance();
  40. private IntWritable result = new IntWritable();
  41. public UDFYear() {
  42. }
  43. /**
  44. * Get the year from a date string.
  45. *
  46. * @param dateString
  47. * the dateString in the format of "yyyy-MM-dd HH:mm:ss" or
  48. * "yyyy-MM-dd".
  49. * @return an int from 1 to 12. null if the dateString is not a valid date
  50. * string.
  51. */
  52. public IntWritable evaluate(Text dateString) {
  53. if (dateString == null) {
  54. return null;
  55. }
  56. try {
  57. Date date = formatter.parse(dateString.toString());
  58. calendar.setTime(date);
  59. result.set(calendar.get(Calendar.YEAR));
  60. return result;
  61. } catch (ParseException e) {
  62. return null;
  63. }
  64. }
  65. }