关闭

UDF函数:日期加减

标签: UDFUDF函数Hadoop
128人阅读 评论(0) 收藏 举报
分类:

@param : date = “20161221” add = “-1”
@return : 20161220” */

package com.chen.udf;

import java.util.Calendar;
import java.util.GregorianCalendar;
/**
 *@param :  date = "20161221" 
 *          add = "-1"
 *@return : "20161220"
 */
public class UdfAddDays {

    public String evaluate(String date,String add){
        int year = Integer.parseInt(date.substring(0, 4));
        int month = Integer.parseInt(date.substring(4,6));
        int day = Integer.parseInt(date.substring(6,8));
        //判断如果传入的日期的月份大于12或者小于1,则返回空
        if(month > 12 || month < 1){
            return "";
        }
        int addDate = Integer.parseInt(add);
        Calendar c = new GregorianCalendar();
        //此处0表示的是一月,故月份减一;
        c.set(year, month-1, day);
        //调用后 day字段的值减去调用前day字段的值等于 addDate;
        c.add(Calendar.DAY_OF_MONTH, addDate);

        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH) + 1;
        day = c.get(Calendar.DAY_OF_MONTH);
        return year + "" + (month < 10 ? "0" + month : month) + "" + (day < 10 ? "0" + day : day);
    }

    public String evaluate(String date,int add){
        int year = Integer.parseInt(date.substring(0, 4));
        int month = Integer.parseInt(date.substring(4,6));
        int day = Integer.parseInt(date.substring(6,8));
        if(month > 12 || month < 1){
            return "";
        }
        Calendar c = new GregorianCalendar();
        c.set(year, month-1, day);
        c.add(Calendar.DAY_OF_MONTH, add);
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH) + 1;
        day = c.get(Calendar.DAY_OF_MONTH);
        return year + "" + (month < 10 ? "0" + month : month) + "" + (day < 10 ? "0" + day : day);
    }

    public static void main(String[] args) {
        UdfAddDays ad = new UdfAddDays();
        System.out.println(ad.evaluate("20161221", "-1")); //20161220
        System.out.println(ad.evaluate("20161221", "15")); //20170105
        System.out.println(ad.evaluate("20161221", 10)); //20161231
    }
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:6324次
    • 积分:359
    • 等级:
    • 排名:千里之外
    • 原创:27篇
    • 转载:10篇
    • 译文:1篇
    • 评论:0条
    文章分类