2012-12-08 263 views
0

我正在开发一个Java Swing应用程序,该应用程序在一周的特定日期和时间发送报告,例如报告时间为星期三09:00:00。我正在尝试使用报告时间计算当前日期和时间之间的时差。例如:日期和时间之间的时差

DayTime1 = “星期三09:00:00”
DayTime2 = “星期二13:00:00”

如何计算这两个值之间的时间差?我自己尝试过,但我甚至无法接近结果。

+2

如果是Date对象,则date1.getTime() - date2.getTime()将以毫秒为单位给出diff。 – Subin

+0

SubinS是正确的。你想看到什么格式的结果? – xagyg

+1

你应该总是发布你试过的代码,即使它没有工作。它有助于证明你已经为这个问题付出了一些努力,它可能会给你提供比你的问题更多的信息。所以,请发布您的代码。 –

回答

2

您需要将字符串创建为Date对象,然后计算两个实例之间的持续时间。

DateFormat dateformat = new SimpleDateFormat("EEE HH:mm:ss"); 
Date date1 = dateformat.parse(dayTime1); 
Date date2 = dateformat.parse(dayTime2); 
getDuration(date1, date2, Calendar.MINUTE); 

public static long getDuration(Date returnTime, Date leaveTime, int scale) { 
     long durationInMillis = returnTime.getTime() - leaveTime.getTime(); 
     switch (scale) { 
      case Calendar.MINUTE: 
       return durationInMillis/ONE_MINUTE_IN_MILLIS; 
      case Calendar.MILLISECOND: 
       return durationInMillis; 
      case Calendar.SECOND: 
       return durationInMillis/ONE_SECOND_IN_MILLIS; 
      case Calendar.HOUR: 
       return durationInMillis/ONE_HOUR_IN_MILLIS; 
      case Calendar.DAY_OF_YEAR: 
      case Calendar.DATE: 
       return durationInMillis/ONE_DAY_IN_MILLIS; 
     } 
     throw new IllegalArgumentException("invalid scale specified"); 
    }