Hive UDF’S addMonths
our project use hive 0.10 , and in the hiveql , we need use addMonths function builtin in hive-0.11.
so I write this udf and test.
java code:
package myudf; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import org.apache.hadoop.hive.ql.exec.UDF; public class addMonths extends UDF { final Calendar calendar = Calendar.getInstance(); // String Year_month int numMonths // return date add public String evaluate(String _date, int numMonths) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); addMonth(sdf.parse(_date), numMonths); int month = calendar.get(Calendar.MONTH) + 1; String strmonth = String.valueOf(month > 9 ? month : "0" + month); String strYearMon = calendar.get(Calendar.YEAR) + strmonth; return strYearMon; } Calendar addMonth(Date d, int numMonths) { calendar.setTime(d); boolean lastDatOfMonth = isLastDayOfMonth(calendar); calendar.add(Calendar.MONTH, numMonths); if (lastDatOfMonth) { int maxDd = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); calendar.set(Calendar.DAY_OF_MONTH, maxDd); } return calendar; } boolean isLastDayOfMonth(Calendar cal) { int maxDd = cal.getActualMaximum(Calendar.DAY_OF_MONTH); int dd = cal.get(Calendar.DAY_OF_MONTH); return dd == maxDd; } }
cd workspace and project folder. then
jar cvf myudf.jar ./
move to proper folder: mv myudf.jar /home/hadoop/jar/myudf.jar
add jar /home/hadoop/jar/myudf.jar;
create temporary function addMonths as "myudf.addMonths";
select addMonths('2012-03-03',2) as newdate, addMonths('2012-03-03',-2) as newdate2 from nums where num<2;
Looking for a job working at Home about MSBI