Calendar.add()后日历返回错误的毫秒数

时间:2013-06-16 14:45:35

标签: java android

final Date now = new Date();
Calendar c = Calendar.getInstance();
final Calendar cal = Calendar.getInstance();
cal.setTime(now); 
cal.add(Calendar.HOUR_OF_DAY, 3); 
SetTime(c.getTimeInMillis());  

getTimeInMillis在我拥有它的同时返回。不是+3小时

如何正确添加当前时间?

1 个答案:

答案 0 :(得分:4)

您将3个小时添加到另一个日历实例。

尝试:

final Date now = new Date();
final Calendar cal = Calendar.getInstance();
cal.setTime(now); 
cal.add(Calendar.HOUR_OF_DAY, 3); 
SetTime(cal.getTimeInMillis());  

正如Peter Lawrey和Brian Roach所说,没有必要创建Date对象。所以你可以这样做:

final Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR_OF_DAY, 3); 
SetTime(cal.getTimeInMillis());