-1

In my project, I need to find duration of staying outside in office time of an employee from goToVisitTime and returnTime. The main concerning point is goToVisitTime and returnTime both are date (java.util) type [getting from other method, can't change anymore] and styingOutSideTime also must be date (java.util) type. For example:

Date goTOvisitTime = "12:25";
Date returnTime = "14:19";

So, output should be like,

styingOutSideTime = "01:54";

Therefore my method looks like below:

public Date getDiffTime(Date goTOvisitTime, Date returnTime) {

//calculate difference 

return styingOutSideTime;
}

I have spent lots of time to determine the solution. I tried to use almost all of Date and Time from Java and Joda Time as well. Additionally, I went through the following links

How to calculate time difference in java?

Java how to calculate time differences

Convert seconds value to hours minutes seconds?

How to get hour/minute difference in java

However, almost all of the solutions are either parameter or return value is a string. additionally, returning either hour or minute only.

xingbin
  • 27,410
  • 9
  • 53
  • 103
Abdur Rahman
  • 1,420
  • 1
  • 21
  • 32
  • 1
    How the difference between the two dates will be a date is possible? So, your method `getDiffTime` should not return Date. – Amit Bera Feb 09 '19 at 17:39
  • Yes, this is the problem that how I can return value "hh: mm" format and it would be treated as Date type whereas we can format Date as "hh: mm" format. --@AmitBera – Abdur Rahman Feb 09 '19 at 17:46
  • Just return the String in the format `hh:mm` – Amit Bera Feb 09 '19 at 18:04
  • 1
    As far as I can see, it’s in [this answer to the last question you linked to](https://stackoverflow.com/a/39553805/5772882). – Ole V.V. Feb 09 '19 at 20:33
  • 1
    I recommend you don’t use `Date`. That class is poorly designed and long outdated. Instead use `LocalTime` and `Duration`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Feb 09 '19 at 20:35

1 Answers1

2

First of all, the duration should not be a Date, it should be a java.time.Duration.

If you only want to the hour part and the minute part, you can do it like this:

Duration duration = Duration.between(goTOvisitTime.toInstant(), returnTime.toInstant());

int hours = duration.toHoursPart();
int minutes = duration.toMinutesPart();

String formattedDuration =  String.format("%02d:%02d", hours, minutes);
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
xingbin
  • 27,410
  • 9
  • 53
  • 103