【2017.6.5】Calendar的HOUR_OF_DAY和MILLISECOND

工作笔记,记录下Calendar使用中容易忽略的问题,测试代码如下:


public class Test {

    public static void main(String[] args){
        //比较Calendar.HOUR_OF_DAY和Calendar.HOUR区别
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar firstCal = Calendar.getInstance();
        firstCal.set(Calendar.HOUR_OF_DAY, 0);
        firstCal.set(Calendar.MINUTE, 0);
        firstCal.set(Calendar.SECOND, 0);
        firstCal.set(Calendar.MILLISECOND, 0);
        String firstStr = dateFormat.format(firstCal.getTime());
        System.out.println("通过HOUR_OF_DAY设置小时" + firstStr);

        Calendar secondCal = Calendar.getInstance();
        secondCal.set(Calendar.HOUR, 0);
        secondCal.set(Calendar.MINUTE, 0);
        secondCal.set(Calendar.SECOND, 0);
        secondCal.set(Calendar.MILLISECOND, 0);
        String secondStr = dateFormat.format(secondCal.getTime());
        System.out.println("通过HOUR设置小时" + secondStr);

        //比较不设置毫秒数和设置毫秒数的差异
        Calendar threeCal = Calendar.getInstance();
        threeCal.set(Calendar.HOUR, 0);
        threeCal.set(Calendar.MINUTE, 0);
        threeCal.set(Calendar.SECOND, 0);
        System.out.println("设置毫秒数为0的总毫秒数" + secondCal.getTimeInMillis() + "毫秒值为" + secondCal.get(Calendar.MILLISECOND));
        System.out.println("没设毫秒数为0的总毫秒数" + threeCal.getTimeInMillis() + "毫秒值为" + threeCal.get(Calendar.MILLISECOND));
    }
}


【2017.6.5】Calendar的HOUR_OF_DAY和MILLISECOND_第1张图片


总结:

1.设置小时时,使用HOUR_OF_DAY,24小时制,HOUR表示的是12小时制

2.尽量设置Calendar.MILLISECOND,防止Calendar(yyyy-MM-dd)和date(yyyy-MM-dd)比较时,因为毫秒不一致,导致normDateConpareResult不为0


int normDateCompareResult = healthUserNormStatistics.getNormDate().compareTo(today.getTime());




你可能感兴趣的:(工作日记)