hive的UDF函数⽰例==时间格式转换
UDF函数实现⼀⾏输⼊对应⼀个输出。
在Hive中提供了时间格式到时间戳的转换,但是对于特殊的时间格式需要做⼀个预处理。⽐如"31/Aug/2015:00:04:37 +0800" 这种形式,需要将它解析成可以识别的时间格式,⽽且要去掉⾸尾的双引号
package com.rabbit.hadoop.hive.udf;
ParseException;
SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.apachemons.lang.StringUtils;
import org.apache.hadoop.UDF;
import org.apache.hadoop.io.Text;
public class UdfDateFormat extends UDF {
// "31/Aug/2015:00:04:37 +0800"
private SimpleDateFormat inputdate = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss",Locale.ENGLISH);
private SimpleDateFormat outputdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedString = null;
public Text evaluate(Text input) {
if (input == null) {
日期转字符串函数return null;
}
String str = String();
if(StringUtils.isBlank(str)) {
return null;
}
str = placeAll("\"", "");
try {
//解析输⼊时间格式
Date parseDate = inputdate.parse(str);
//格式化成字符串
formattedString = outputdate.format(parseDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new Text(formattedString);
}
// public static void main(String[] args) {
// System.out.println(new UdfDateFormat().evaluate(new Text("\"31/Aug/2015:00:04:37 +0800\"")));
// }
}
可以将这个程序打成jar包,上传到服务器,定义成Hive的临时function或者永久function。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。