如何比较两个timeStamp并从中获得差异。我试图获得两个不同timeStamps之间的持续时间。使用日期,但我在比较时遇到异常。
我如何得到timeStamp 01-08-2013 06:19:35
我得到的异常就像 java.text.ParseException:Unparseable 日期:“01-08-2013 06:19:35”
答案 0 :(得分:5)
将日期转换为毫秒,然后您可以使用
long difference = finalDate.getTime() - initialDate.getTime();
关于您的ParseException
,解析日期格式化程序的模式有问题。如果您要解析"dd-MM-yyyy HH:mm:ss"
"01-08-2013 06:19:35"
或者,您可以使用Joda-Time库并按以下方式查找时差:
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MM-yyyy HH:mm:ss");
DateTime finalDate = formatter.parse("someDate1");
DateTime initialDate = formatter.parse("someDate2");
Interval interval = new Interval(finalDate, initialDate);
答案 1 :(得分:-1)
Calendar thatDay = Calendar.getInstance();
thatDay.set(Calendar.DAY_OF_MONTH,25);
thatDay.set(Calendar.MONTH,7); // 0-11 so 1 less
thatDay.set(Calendar.YEAR, 1985);
Calendar today = Calendar.getInstance(); //THIS IS TO GET TODAY DATE, you can simpy use your two dates
long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
这是一个近似值......
long days = diff / (24 * 60 * 60 * 1000);
PLUS :要从字符串中解析日期,可以使用
String strThatDay = "1985/08/25";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Date d = null;
try {
d = formatter.parse(strThatDay);//catch exception
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Calendar thatDay = Calendar.getInstance();
thatDay.setTime(d); //rest is the same....