使用Calendar获取时间分量

来源:互联网 发布:多个数字比大小算法 编辑:程序博客网 时间:2024/05/20 21:49

使用Calendar获取时间分量
1.生成实例

   Calendar cal1 = Calendar.getInstance();

2.设置 时间 按照:年 月 日 时 分 秒

 cal1.set(cal1.get(Calendar.YEAR),cal1.get(Calendar.MONDAY), cal1.get(Calendar.DAY_OF_MONTH), 0, 0,0);

3.时间获得相差的天数

      // 得微秒级时间差     long val = calendarEnd.getTimeInMillis() - calendarBegin.getTimeInMillis();     // 换算后得到天数     long day = val / (1000 * 60 * 60 * 24);

3.例子

       Calendar cal1 = Calendar.getInstance();        Calendar cal2 = Calendar.getInstance();        if("day".equals("timeZone")){     //时间分量  当天            cal1.set(cal1.get(Calendar.YEAR),cal1.get(Calendar.MONDAY), cal1.get(Calendar.DAY_OF_MONTH), 0, 0,0);            cal2.set(cal2.get(Calendar.YEAR),cal2.get(Calendar.MONDAY), cal2.get(Calendar.DAY_OF_MONTH), 0, 0,0);            cal2.set(Calendar.HOUR_OF_DAY, 24);        }        if("month".equals("timeZone")){     //时间分量  当月            cal1.set(cal1.get(Calendar.YEAR),cal1.get(Calendar.MONDAY), cal1.get(Calendar.DAY_OF_MONTH), 0, 0,0);            cal1.set(Calendar.DAY_OF_MONTH,cal1.getActualMinimum(Calendar.DAY_OF_MONTH));            cal2.set(cal2.get(Calendar.YEAR),cal2.get(Calendar.MONDAY), cal2.get(Calendar.DAY_OF_MONTH), 0, 0,0);            cal2.set(Calendar.DAY_OF_MONTH,cal2.getActualMaximum(Calendar.DAY_OF_MONTH));            cal2.set(Calendar.HOUR_OF_DAY, 24);        }        if("Quarterly".equals("timeZone")){  //当前 季度               int currentMonth = cal1.get(Calendar.MONTH) + 1;                if (currentMonth >= 1 && currentMonth <= 3) {                     //一季度                    cal1.set(cal1.get(Calendar.YEAR),0, 1, 0, 0,0);                    cal2.set(cal1.get(Calendar.YEAR),3, 0, 0, 0,0);                } else if (currentMonth >= 4 && currentMonth <= 6) {                     //二季度                    cal1.set(cal1.get(Calendar.YEAR),3, 1, 0, 0,0);                    cal2.set(cal1.get(Calendar.YEAR),6, 0, 0, 0,0);                } else if (currentMonth >= 7 && currentMonth <= 9) {                     //三季度                    cal1.set(cal1.get(Calendar.YEAR),6, 1, 0, 0,0);                    cal2.set(cal1.get(Calendar.YEAR),9, 0, 0, 0,0);                } else if (currentMonth >= 10 && currentMonth <= 12) {                     //四季度                    cal1.set(cal1.get(Calendar.YEAR),9, 1, 0, 0,0);                    cal2.set(cal1.get(Calendar.YEAR),12, 0, 0, 0,0);                }        }        if("year".equals("timeZone")){   //当前年份            cal1.set(cal1.get(Calendar.YEAR),0, 1, 0, 0,0);            cal2.set(cal2.get(Calendar.YEAR)+1,0, 0, 0, 0,0);        }
0 0
原创粉丝点击