0

如何比较两个 timeStamp 并从中获得差异。我正在尝试获取两个不同时间戳之间的持续时间。使用日期,但我在比较时遇到异常。

这就是我获得时间戳的方式 01-08-2013 06:19:35

我收到类似java.text.ParseException: Unparseable date: "01-08-2013 06:19:35"的异常

4

2 回答 2

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);
于 2013-08-02T14:22:41.287 回答
-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....
于 2013-08-02T14:22:27.447 回答