Solved

# How to calcuate time duration from 2 time strings?

Posted on 2011-03-21
681 Views
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.
0
Question by:OliviaRedhorse
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• 12
• 9
• 3
• +2

LVL 47

Accepted Solution

for_yan earned 322 total points
ID: 35183045
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
0

LVL 86

Assisted Solution

CEHJ earned 71 total points
ID: 35183047
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
0

LVL 47

Assisted Solution

for_yan earned 322 total points
ID: 35183063
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();
0

LVL 47

Assisted Solution

for_yan earned 322 total points
ID: 35183081
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();

0

LVL 47

Assisted Solution

for_yan earned 322 total points
ID: 35183097
If you just use this pattern ("HH:mm:ss.SSS") I don't think SimpleDateFormat will require date
0

LVL 47

Assisted Solution

for_yan earned 322 total points
ID: 35183118

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
``````
0

LVL 86

Expert Comment

ID: 35183129
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);
}
``````
0

LVL 86

Expert Comment

ID: 35183176
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();
}
``````
0

LVL 86

Expert Comment

ID: 35183190
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();
}
``````
0

Author Comment

ID: 35184652
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.
0

Author Comment

ID: 35184669
One more question.  Should I be concerned that when I am only working with time, the date is defaulted to 1/1/1970?
0

LVL 47

Assisted Solution

for_yan earned 322 total points
ID: 35184673

I think if you turn it back make
new Date(long time difference)
and format it through SimpleDateFormat with the same pattern
0

LVL 47

Assisted Solution

for_yan earned 322 total points
ID: 35184691
this does not matter in this case about the year
0

LVL 86

Expert Comment

ID: 35184694
>> 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
0

LVL 92

Assisted Solution

objects earned 71 total points
ID: 35184846
>  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
0

LVL 86

Expert Comment

ID: 35184908
You can actually just use the same DateFormat and do
``````String hms_ms = df.format(new Date(diff));
``````
0

LVL 47

Expert Comment

ID: 35184967

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

0

LVL 47

Expert Comment

ID: 35184973
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

0

LVL 92

Expert Comment

ID: 35185005
If you read the link I posted above it explains that you can only use DateFormat if the period is less than 24 hours.
0

LVL 86

Expert Comment

ID: 35185017
Sorry yes - on the DateFormat, you'd need to do
``````df.setTimeZone(TimeZone.getTimeZone("UTC"));
``````
0

LVL 47

Expert Comment

ID: 35185025

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);

0

LVL 86

Expert Comment

ID: 35185031
...so
``````f.setTimeZone(TimeZone.getTimeZone("UTC"));
String ss = f.format(d3);
``````
0

LVL 47

Assisted Solution

for_yan earned 322 total points
ID: 35185052
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
``````
0

LVL 92

Assisted Solution

objects earned 71 total points
ID: 35185053
> 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
0

LVL 4

Assisted Solution

msk_apk earned 36 total points
ID: 35186526
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.

0

LVL 47

Assisted Solution

for_yan earned 322 total points
ID: 35186601

@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.

0

LVL 86

Assisted Solution

CEHJ earned 71 total points
ID: 35188402
If it were not important, then new Date(0L) would give you the reference time. Most often it won't
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java. Â For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient. Â  However, when your application has viâ€¦
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used byâ€¦
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define â€¦
This video teaches viewers about errors in exception handling.
###### Suggested Courses
Course of the Month8 days, 10 hours left to enroll