@Test
public void fun3() throws ParseException {
Calendar origin = Calendar.getInstance();
origin.set(2000, 0, 1);
System.out.println("calendar:2000-01-01\t" + origin.getTimeInMillis());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = simpleDateFormat.parse("2000-01-01");
System.out.println("date:2000-01-01\t" + date.getTime());
origin.set(2000, 0, 1, 0, 0, 0);
System.out.println("calendar:2000-01-01 00:00:00\t" + origin.getTimeInMillis());
simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
date = simpleDateFormat.parse("2000-01-01 00:00:00\t");
System.out.println("date:2000-01-01 00:00:00\t" + date.getTime());
}
结果:
calendar:2000-01-01 946696419672
date:2000-01-01 946656000000
calendar:2000-01-01 00:00:00 946656000672
date:2000-01-01 00:00:00 946656000000
可以看到使用Date两次获取的结果是一致的。而Calendar有较大差异,且多次运行结果不一致。
推荐使用Date来获取指定时间点的毫秒值。
原因是Calendar.getInstance()时候,会给Calendar赋值为当前时间的毫秒值,调用set方法会根据参数对年、月、日、时、分、秒对应的值进行替换。然而无法对毫秒值进行替换,所以毫秒值是创建Calendar对象时的毫秒值。
@Test
public void fun4(){
Calendar origin = Calendar.getInstance();
System.out.println(origin.getTimeInMillis());
origin.set(2000, 0, 1);
System.out.println(origin.getTimeInMillis());
origin.set(2000, 0, 1,0,0,0);
System.out.println(origin.getTimeInMillis());
}
//输出结果为:
//1562047167241
//946706367241
//946656000241