开发者

Time Duration problem

开发者 https://www.devze.com 2023-01-24 12:38 出处:网络
I am not able to get the correct Time duration.So can anyone please help me in finding the solution //code

I am not able to get the correct Time duration.So can anyone please help me in finding the solution

//code

 public static String getDateDifference(java.util.Date start, java.util.Date end) {
    logger.info("Enter getDateDifference ");
    Calendar startCal = Calendar.getInstance();
    startCal.setTime(start);
    Calendar endCal = Calendar.getInstance();
    endCal.setTime(end);

    int hourDiff = Math.abs(endCal.get(Calendar.HOUR_OF_DAY) - startCal.get(Calendar.HOUR_OF_DAY));
    int minDiff开发者_StackOverflow = Math.abs(endCal.get(Calendar.MINUTE) - startCal.get(Calendar.MINUTE));
    String diff = Integer.toString(hourDiff) + ":" + Integer.toString(minDiff);

    logger.info("Date Difference : " + diff);
    logger.info("Exit getDateDifference ");
    return diff;
}


Won't this fail if the start is 23:59 and the end 00:01?

Instead just get the milliseconds from the two dates, subtract and then convert to hours and minutes.

long millis = end.getTime() - start.getTime();
long seconds = millis/1000L;
long hours = seconds/3600L;
long mins = (seconds % 3600L) / 60L;


If you can use JodaTime this becomes fairly trivial. Like so:

Period period = new Period( new DateTime( start ), new DateTime( end ), PeriodType.time() );
return period.getHours() + ":" + period.getMinutes();


why don't you do the following

1) convert your 2 Dates to a common unit (here hours)

2) calculate the difference

3) transform the result to a format you want (Date, string ...)

I don't have the code handy but it should be fairly straight forwards.

your method is open to small errors like forgetting to increment/decrement a day when you go above 24h or under 0h. also it will be diffcult to maintain if you want to suddenly add minutes and seconds ...

hope this helps

Jason

0

精彩评论

暂无评论...
验证码 换一张
取 消