1. 程式人生 > >hive自定義函式(8位日期相差月份數)

hive自定義函式(8位日期相差月份數)


package com.udf;
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 MonthDiff extends UDF {
	public int evaluate(String sdate,String edate ) throws ParseException{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		Date start = sdf.parse(sdate);
		Date end = sdf.parse(edate);

		Calendar startCalendar = Calendar.getInstance();  
        startCalendar.setTime(start);  
        
        Calendar endCalendar = Calendar.getInstance();  
        endCalendar.setTime(sdf.parse(edate));  
        
        Calendar temp = Calendar.getInstance();  
        temp.setTime(sdf.parse(edate));  
        temp.add(Calendar.DATE, 1);  
  
        int year = endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR);  
        int month = endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH);  
  
        if ((startCalendar.get(Calendar.DATE) == 1)&& (temp.get(Calendar.DATE) == 1)) {  
            return year * 12 + month + 1;  
        } else if ((startCalendar.get(Calendar.DATE) != 1) && (temp.get(Calendar.DATE) == 1)) {  
            return year * 12 + month;  
        } else if ((startCalendar.get(Calendar.DATE) == 1) && (temp.get(Calendar.DATE) != 1)) {  
            return year * 12 + month;  
        } else {  
            return (year * 12 + month - 1) < 0 ? 0 : (year * 12 + month);  
        }  
		
	}
	
	public static void main(String[] args) throws ParseException {
		MonthDiff monthDiff = new MonthDiff();
		int evaluate = monthDiff.evaluate("2016-2-1", "2018-6-4");
		System.out.println(evaluate);
	}

}

目錄結構:


匯出jar:


在hive中執行以下命令:

add jar /root/dev/test_month_diff.jar

create temporary function f_monthdiff as 'com.udf.MonthDiff';  --'com.udf.MonthDiff'為類路徑'。