java时间段增加、减少工具(含代码)

当我们遇上一些时间上的问题的时候就会出现一种疑惑,比如给会员续费的时候如何在原会员过期时间的基础上增加一个时间段呢?前些天在公司处理业务的时候遇上这个问题,于是自己写了一个时间段增加与减少的工具类。


附上代码:


/**
 * 通过计算获取增加时间或者减少时间
 * 参数1、当前时间,2、增加还是减少标识符,3、时间段(天,周,月,季,半年,年),4、数量
 */
public static Date test(Date currentData, Boolean isAdd, String type, Integer number) {
    //获取时间格式
    Calendar cal = Calendar.getInstance();
    if (currentData == null) {
        cal.setTime(new Date());
    } else {
        cal.setTime(currentData);
    }
    switch (type) {
        case "year":
            if (isAdd) {
                cal.add(Calendar.YEAR, number);
            } else
                cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) - number);
            break;
        case "halfYear":
            if (isAdd) {
                cal.add(Calendar.MONTH, +6);
            } else
                cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 6);
            break;
        case "season":
            if (isAdd) {
                cal.add(Calendar.MONTH, +3);
            } else
                cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 3);
            break;
        case "month":
            if (isAdd) {
                cal.add(Calendar.MONTH, +1);
            } else
                cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1);
            break;
        case "week":
            if (isAdd) {
                cal.add(Calendar.DATE, +7);
            } else
                cal.set(Calendar.DATE, cal.get(Calendar.DATE) - 7);
            break;
        case "day":
            if (isAdd) {
                cal.add(Calendar.DATE, +number);
            } else
                cal.set(Calendar.DATE, cal.get(Calendar.DATE) - number);
            break;
        default:
            if (isAdd) {
                cal.add(Calendar.DATE, +number);
            } else
                cal.set(Calendar.DATE, cal.get(Calendar.DATE) - number);
            break;
    }
    return cal.getTime();
}


测试代码:

public static void main(String[] arg) {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = test(new Date(), true, "year", 1);
    String date1 = simpleDateFormat.format(date);
    String date2 = simpleDateFormat.format(new Date());
    System.out.println(date2 + "==============" + date1);
}
测试结果:

2017-11-13 11:20:55==============2018-11-13 11:20:55

Process finished with exit code 0


=====================分割线===================================================

电影《肖申克的救赎》里有个词“体制化(institutionalizing)“。虽然我们不是在监狱那种体制化,但我们在生活中是否存在某种“体制化”呢?



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值