Java中对日期常见的操作实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/XUEER88888888888888/article/details/85463363

    /*
     * 现在日期和查询日期先后比较
     * month  输入以现在为基准,往前推的n个月
     *
     */
    public static boolean DateCompa(Integer month, Date orgQueryDate) {

        Date nowDate = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(nowDate);
        c.add(Calendar.MONTH, month);//过去n个月
        Date time = c.getTime(); //得到加工后的日期

        //日期中越大越后
        if (orgQueryDate.before(time)) {
            return false;
        } else {
            return true;
        }


    }




    /*
     * 传入两日期计算年龄
     * eg 2018/12/13-1995/12/14 22岁 2018/12/15-1995/12/14 23岁 就算差一天也是小一岁
     *
     */
    public static int getAge() {

        LocalDate date1 = LocalDate.of(2018, 12, 13);
        LocalDate date2 = LocalDate.of(1995, 12, 14);
        int age = date2.until(date1).getYears();

        return age;

    }




    /*
     * 对比传入时间与当前时间差别 para 时间 para 类型 按30天一个月计算
     *
     * @throws Exception
     */

    public static Double compareTime(String time, String type) throws Exception {

        Date curDate = new Date();
        String curDateS = "";
        SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd");
        curDateS = df.format(curDate);
        curDate = df.parse(curDateS);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
        Date date = sdf.parse(time);
        long baseT = 1;
        if (type.equals("s")) {  //秒
            baseT = 1000;
        } else if (type.equals("m")) {  //分
            baseT = 1000 * 60;
        } else if (type.equals("h")) {  //小时
            baseT = 1000 * 3600;
        } else if (type.equals("dd")) { //天
            baseT = 1000 * 3600 * 24;
        } else if (type.equals("mm")) { //月
            baseT = 1000 * 3600 * 24 * 30l;
        } else if (type.equals("yy")) { //年
            baseT = 1000 * 3600 * 24 * 30l * 12l;
        }

        Double result = (Double) (((curDate.getTime() + 0.00) - (date.getTime() + 0.00)) / (baseT));
        return result;
    }

猜你喜欢

转载自blog.csdn.net/XUEER88888888888888/article/details/85463363