# How to calcuate time duration from 2 time strings?

Hello All,
I am having writers block.  I would like to calculate the time duration from 2 strings that are input by the user.  I know I need to convert the strings to date/time format or integer.  The time strings would look something like this; start time - 10:35:22.189 and end time - 11:41:12.120.  Also, notice I need milliseconds.  Because I am working with just time, I am having trouble determining which calendar/date function to use because they involve using the date as well.  Instead of date, the user is entering the Day of Year, so it is any integer that is within the 1 to 365 days. So, the timestamp format would be 219/10:35:22.189.  What is the best method to use for this calculation? Any resources, recommendations or examples would be very helpful.  Thank you.
###### Who is Participating?

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Commented:
You can use SimpleDateFormat - parse them as time and then getTime() will give you long value in milliseconds - you can then convetrt it into
minutes hours, etc

Experts Exchange Solution brought to you by

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Commented:
You can ignore the date part. Just use a DateFormat of HH:mm:ss:S to parse the String into a Date then

http://technojeeves.com/joomla/index.php/free/71-difference-between-two-dates-in-java
Commented:
SimpleDateFormat f = newSimpleDateFormat("hh:mm:ss.SSS");
Date d1 = f.parse(s1,new ParsePosition(0));
Date d2 = f.parse(s1,new ParsePosition(0));

long msec = d2.getTime() - d1.getTime();
Commented:
This is with some corrections:
String s1 = "10:35:22.189";
String s2 = " 11:41:12.120";

SimpleDateFormat f = newSimpleDateFormat("HH:mm:ss.SSS");
Date d1 = f.parse(s1,new ParsePosition(0));
Date d2 = f.parse(s2,new ParsePosition(0));

long msec = d2.getTime() - d1.getTime();

Commented:
If you just use this pattern ("HH:mm:ss.SSS") I don't think SimpleDateFormat will require date
Commented:

This is the code
``````     String s1 = "10:35:22.189";
String s2 = " 11:41:12.120";

SimpleDateFormat f = new SimpleDateFormat("HH:mm:ss.SSS");
Date d1 = f.parse(s1,new ParsePosition(0));
Date d2 = f.parse(s2,new ParsePosition(0));

long msec = d2.getTime() - d1.getTime();

System.out.println("msec:" + msec);
``````

This is the result:
``````msec:3949931
``````
Commented:
e.g.
``````public static long timeDiff(String t1, String t2) throws ParseException {
//10:35:22.189 and end time - 11:41:12.120.
DateFormat df = new SimpleDateFormat("HH:mm:ss.S");
Date start = df.parse(t1);
Date end =  df.parse(t2);
return TimeDiff.getTimeDifference(start, end, TimeDiff.TimeField.MILLISECOND);
}
``````
Commented:
Oh sorry - if you want all milliseconds, it's better to use for_yan's method, which can be simplified:

``````public static long timeDiff(String t1, String t2) throws ParseException {
DateFormat df = new SimpleDateFormat("HH:mm:ss.S");
return df.parse(t2).getTime() - df.parse(t1).getTime();
}
``````
Commented:
With clearer naming:
``````public static long timeDiff(String startTime, String endTime) throws ParseException {
DateFormat df = new SimpleDateFormat("HH:mm:ss.S");
return df.parse(endTime).getTime() - df.parse(startTime).getTime();
}
``````
Author Commented:
Thank you for your quick responses.

In using the end.getTime() - start.getTime() formula, this turns the time difference in milliseconds, correct?  If I need to display the time format HH:mm:ss.SSS, I would need to add logic that converts the milliseconds to hour, minutes and seconds.
Author Commented:
One more question.  Should I be concerned that when I am only working with time, the date is defaulted to 1/1/1970?
Commented:

I think if you turn it back make
new Date(long time difference)
and format it through SimpleDateFormat with the same pattern
Commented:
this does not matter in this case about the year
Commented:
>> If I need to display the time format HH:mm:ss.SSS, I would need to add logic that converts the milliseconds to hour, minutes and seconds.

You could use the code that i originally gave you
Java DeveloperCommented:
>  If I need to display the time format HH:mm:ss.SSS, I would need to add logic that converts the milliseconds to hour, minutes and seconds.

see the following

http://helpdesk.objects.com.au/java/how-to-calculate-the-difference-between-two-dates-or-times

also some background on parsing dates

http://helpdesk.objects.com.au/java/how-do-i-parse-a-java-string-that-specifies-a-date
Commented:
You can actually just use the same DateFormat and do
``````String hms_ms = df.format(new Date(diff));
``````
Commented:

You would think so, but in fact at least SimpleDateFormat (don't now about
when you format

SimpleDateFormat f = new SimpleDateFormat("hh:mm:ss.SSS");
Date d1 = f.parse(s1,new ParsePosition(0));
Date d2 = f.parse(s2,new ParsePosition(0));

long msec = d2.getTime() - d1.getTime();

System.out.println("msec:" + msec);

Date d3 = new Date(msec );
System.out.println("date: " + d3);
String ss = f.format(d3);
System.out.println("ss:" + ss);
returns
17:05:49.931

even though msec returns correctly:

msec: 3949931
(a little bit more than an hour ofr those two points you specified).

Don't understand how it can be

Commented:
You would think so, but in fact it does not work this way:
at least  with SimpleDateFormat
when you format it like that:

SimpleDateFormat f = new SimpleDateFormat("hh:mm:ss.SSS");
Date d1 = f.parse(s1,new ParsePosition(0));
Date d2 = f.parse(s2,new ParsePosition(0));

long msec = d2.getTime() - d1.getTime();

System.out.println("msec:" + msec);

Date d3 = new Date(msec );
System.out.println("date: " + d3);
String ss = f.format(d3);
System.out.println("ss:" + ss);
returns
17:05:49.931

even though msec returns correctly:

msec: 3949931
(a little bit more than an hour ofr those two points you specified).

Don't understand how it can be

Java DeveloperCommented:
If you read the link I posted above it explains that you can only use DateFormat if the period is less than 24 hours.
Commented:
Sorry yes - on the DateFormat, you'd need to do
``````df.setTimeZone(TimeZone.getTimeZone("UTC"));
``````
Commented:

BUt DateFormat gives the same result.
I guess it is about Time Zone or somthing it is because Im in pAcificTome

String s1 = "10:35:22.189";
String s2 = "11:41:12.120";

DateFormat f = new SimpleDateFormat("HH:mm:ss.SSS", Locale.UK);
Date d1 = f.parse(s1,new ParsePosition(0));
Date d2 = f.parse(s2,new ParsePosition(0));

long msec = d2.getTime() - d1.getTime();

System.out.println("msec:" + msec);

Date d3 = new Date(msec );
System.out.println("date: " + d3);
String ss = f.format(d3);
System.out.println("ss:" + ss);

Commented:
...so
``````f.setTimeZone(TimeZone.getTimeZone("UTC"));
String ss = f.format(d3);
``````
Commented:
Yes, with Time Zone it finally works:
``````       String s1 = "10:35:22.189";
String s2 = "11:41:12.120";

DateFormat f = new SimpleDateFormat("HH:mm:ss.SSS", Locale.UK);

f.setTimeZone(TimeZone.getTimeZone("UTC"));

Date d1 = f.parse(s1,new ParsePosition(0));
Date d2 = f.parse(s2,new ParsePosition(0));

long msec = d2.getTime() - d1.getTime();

System.out.println("msec:" + msec);

Date d3 = new Date(msec );
System.out.println("date: " + d3);
String ss = f.format(d3);
System.out.println("ss:" + ss);
``````

``````date: Wed Dec 31 17:05:49 PST 1969
ss:01:05:49.931
``````
Java DeveloperCommented:
> I guess it is about Time Zone or somthing it is because Im in pAcificTome

its nothing to do with timezones.

read the link above where it was shown how to use DateFormat
Commented:
when you would like to compare two time strings, it is necessary to make sure they belong to same year. because if you use default SimpleDateFormat object as given below, it takes the default year 1970.

String format = "D/hh:mm:ss.S";
String dateString = "219/10:35:22.189";
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
Date date = dateFormat.parse(dateString);
System.out.println(date);

To get current year, GregorianCalendar can be used as below

GregorianCalendar parsedDate = new GregorianCalendar();
String pattern = "(\\d+)/(\\d+):(\\d+):(\\d+).(\\d+)";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(dateString);
if(m.find())
{
int dateOfYear = Integer.parseInt(m.group(1));
int hour = Integer.parseInt(m.group(2));
int minute = Integer.parseInt(m.group(3));
int second = Integer.parseInt(m.group(4));
int milliseconds = Integer.parseInt(m.group(5));

parsedDate.set(Calendar.DAY_OF_YEAR,dateOfYear);
parsedDate.set(Calendar.HOUR,hour);
parsedDate.set(Calendar.MINUTE,minute);
parsedDate.set(Calendar.SECOND,second);
parsedDate.set(Calendar.MILLISECOND,milliseconds);
}
System.out.println(parsedDate);

Any one of the above code can be used that suits your need. I believe usage of second code is good, because if you calculate time difference with respect to 1970, it could have some problems as leap year calculation etc. If both the date input strings belong to same/current year, then you will eradicate those issue.

Commented:

@objects

I'm still trying to understand:

http://helpdesk.objects.com.au/java/how-to-calculate-the-difference-between-two-dates-or-times

also sets GMT time zone,
and before I set Time Zone to GMT or UTC, I was getting 17 hours difference instead of 1 hour
That's why I was thinking that it is about Time Zone

So when I use the following code:

``````       String s1 = "10:35:22.189";
String s2 = "11:41:12.120";

DateFormat f = new SimpleDateFormat("HH:mm:ss.SSS");

f.setLenient(false);
f.setTimeZone(TimeZone.getTimeZone("PST"));

Date d1 = f.parse(s1,new ParsePosition(0));
Date d2 = f.parse(s2,new ParsePosition(0));

long msec = d2.getTime() - d1.getTime();

System.out.println("msec:" + msec);

Date d3 = new Date(msec );
System.out.println("date: " + d3);
String ss = f.format(d3);
System.out.println("ss:" + ss);
``````
I get this result:
``````date: Wed Dec 31 17:05:49 PST 1969
ss:17:05:49.931
``````

when I use this code (the only difference is changing "PST" to "GMT")

``````  String s1 = "10:35:22.189";
String s2 = "11:41:12.120";

DateFormat f = new SimpleDateFormat("HH:mm:ss.SSS");

f.setLenient(false);
f.setTimeZone(TimeZone.getTimeZone("GMT"));

Date d1 = f.parse(s1,new ParsePosition(0));
Date d2 = f.parse(s2,new ParsePosition(0));

long msec = d2.getTime() - d1.getTime();

System.out.println("msec:" + msec);

Date d3 = new Date(msec );
System.out.println("date: " + d3);
String ss = f.format(d3);
System.out.println("ss:" + ss);
``````

I get this (correct) result:

``````date: Wed Dec 31 17:05:49 PST 1969
ss:01:05:49.931
``````

That's why I was thinking that Time Zone is important.

Commented:
If it were not important, then new Date(0L) would give you the reference time. Most often it won't
###### It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JSP

From novice to tech pro — start learning today.