java日期工具类

java日期工具类

public class DateUtil {


    public  static <T extends BaseEntity> void setCreateDate(T t ) {

        t.setCreateDate(new Date());

    }



    public  static <T extends BaseEntity> void setUpdateDate(T t ) {

        t.setUpdateDate(new Date());

    }

    public static Date getDate() {
        return new Date();
    }

    /**
     * 判断年份是不是 闰年
     * @param year
     * @return
     */
    public static boolean isLeapYear(int year){
        return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
    }


    /**
     * 将时间转化为 yyyyMMdd 的数值
     * @param d 需要转换的时间
     * @return yyyyMMdd 数组
     */
    public static int getDayNum(Date d){
        Calendar cal = Calendar.getInstance();
        cal.setTime(d);
        int yearNum = cal.get(Calendar.YEAR);
        // ps 月份从0开始
        int monthNum = cal.get(Calendar.MONTH)+1;
        int dayNum = cal.get(Calendar.DAY_OF_MONTH);
        return yearNum*10000 + monthNum * 100 + dayNum;
    }
    /**
     * 计算2个日期之间相差的  以年、月、日为单位,各自计算结果是多少
     * 比如:2011-02-02 到  2017-03-02
     *                                以年为单位相差为:6年
     *                                以月为单位相差为:73个月
     *                                以日为单位相差为:2220天
     * @param fromDate
     * @param toDate
     * @return
     */
    public static Integer dayCompare(String fromDate,String toDate) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
        Date fDate = simpleDateFormat.parse(fromDate);
        Date tDate = simpleDateFormat.parse(toDate);

        Calendar  from  =  Calendar.getInstance();
        from.setTime(fDate);

        Calendar  to  =  Calendar.getInstance();
        to.setTime(tDate);

        int day = (int) ((to.getTimeInMillis()  -  from.getTimeInMillis())  /  (24  *  3600  *  1000));
        return day;
    }

    public static void main(String[] args) {
//        Calendar cal = Calendar.getInstance();
//        System.out.println(getDayNum(cal.getTime()));
//        try {
//            System.out.println(dayCompare("2020-01-01", "2020-12-31"));
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值