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.
OliviaRedhorseAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

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.

for_yanCommented:
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

Your issues matter to us.

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

Start your 7-day free trial
CEHJCommented:
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
for_yanCommented:
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();
Bootstrap 4: Exploring New Features

Learn how to use and navigate the new features included in Bootstrap 4, the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites.

for_yanCommented:
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();


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

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

Open in new window


This is the result:
msec:3949931

Open in new window

CEHJCommented:
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);
    }

Open in new window

CEHJCommented:
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();
    }

Open in new window

CEHJCommented:
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();
    }

Open in new window

OliviaRedhorseAuthor 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.
OliviaRedhorseAuthor Commented:
One more question.  Should I be concerned that when I am only working with time, the date is defaulted to 1/1/1970?
for_yanCommented:

I think if you turn it back make
new Date(long time difference)
and format it through SimpleDateFormat with the same pattern
for_yanCommented:
this does not matter in this case about the year
CEHJCommented:
>> 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
Mick BarryJava 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
CEHJCommented:
You can actually just use the same DateFormat and do
String hms_ms = df.format(new Date(diff));

Open in new window

for_yanCommented:


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

instead of 01: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







for_yanCommented:
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

instead of 01: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




Mick BarryJava 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.
CEHJCommented:
Sorry yes - on the DateFormat, you'd need to do
df.setTimeZone(TimeZone.getTimeZone("UTC"));

Open in new window

for_yanCommented:

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

CEHJCommented:
...so
f.setTimeZone(TimeZone.getTimeZone("UTC"));
String ss = f.format(d3);

Open in new window

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

Open in new window


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

Open in new window

Mick BarryJava 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
msk_apkCommented:
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.

for_yanCommented:

@objects

I'm still trying to understand:

Your link

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

Open in new window

I get this result:
date: Wed Dec 31 17:05:49 PST 1969
ss:17:05:49.931

Open in new window


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

Open in new window


I get this (correct) result:

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

Open in new window


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

CEHJCommented:
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.