2011-11-29 75 views
1

我试图比较Java中的两个毫秒值。一个来自日历,另一个来自System.currentTimeMillis()。但是,日历中的值似乎总是远大于来自System.currentTimeMillis()的值。与日历的毫秒差距太大

为了构建日历,我使用格式dd/MM/yyyy HH:mm解析日期字符串,并将它的参数部分放入日历中(为简洁起见,省略了try-catch)。

Calendar obCal = null; 

//Exception here shows invalid format 
DateFormat DF = new SimpleDateFormat("dd/MM/yyyy HH:mm"); 
DF.parse(Date); 

//Example string: 29/11/2011 16:30 
String[] parts = Date.split("/"); 

obCal = Calendar.getInstance(); 
int Y = Integer.parseInt(parts[2].split(" ")[0]); 
int m = Integer.parseInt(parts[1]); 
int d = Integer.parseInt(parts[0]); 
int H = Integer.parseInt(parts[2].split(" ")[1].split(":")[0]); 
int M = Integer.parseInt(parts[2].split(" ")[1].split(":")[1]); 

obCal.set(Calendar.YEAR, Y); 
obCal.set(Calendar.MONTH, m); 
obCal.set(Calendar.DAY_OF_MONTH, d); 
obCal.set(Calendar.HOUR_OF_DAY, H); 
obCal.set(Calendar.MINUTE, M); 
obCal.set(Calendar.SECOND, 0); 
obCal.set(Calendar.MILLISECOND, 0); 

检查日历后显示我它正在收到正确的日期和时间。然后我得到了毫秒值,因为从obCal.getTimeInMillis()时代并将其存储为秒数为long

long stamp = obCal.getTimeInMillis()/1000L; 

当我到达日期字符串表示的时间,并从日历比较时间戳时间戳System.currentTimeMillis() ,我发现前者要大得多。当前时间和日历时间(curTime-calTime)之间的差异通常在-2,500,000的地方

可能是什么原因造成的? 谢谢

+1

你为什么不只需使用'Calendar#setTime(...)'? – Thomas

+2

为什么不使用'obCal.setTime(DF.parse(date));'? – BalusC

回答

7

月是基于0,所以当你做obCal.set(Calendar.MONTH, m);你是1个月。

+0

+1 2500000秒约为28.9天。好的地方。 –

+0

谢谢!我一直在盯着这个问题好几个小时,而这已经解决了。 – AndyBursh

0

最有可能你错过了日历API定义一个月在范围为0〜11,当你分析它为1到12,使一个30 * 86400第二个区别...