Solved

How to calcuate time duration from 2 time strings?

Posted on 2011-03-21
27
674 Views
Last Modified: 2012-05-11
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
Comment
Question by:OliviaRedhorse
  • 12
  • 9
  • 3
  • +2
27 Comments
 
LVL 47

Accepted Solution

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

by:CEHJ
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

by:for_yan
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

by:for_yan
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

by:for_yan
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

by:for_yan
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);

Open in new window


This is the result:
msec:3949931

Open in new window

0
 
LVL 86

Expert Comment

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

Open in new window

0
 
LVL 86

Expert Comment

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

Open in new window

0
 
LVL 86

Expert Comment

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

Open in new window

0
 

Author Comment

by:OliviaRedhorse
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

by:OliviaRedhorse
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

by:for_yan
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

by:for_yan
for_yan earned 322 total points
ID: 35184691
this does not matter in this case about the year
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 86

Expert Comment

by:CEHJ
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

by:objects
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

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

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
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

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







0
 
LVL 47

Expert Comment

by:for_yan
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

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




0
 
LVL 92

Expert Comment

by:objects
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

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

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
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

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

Open in new window

0
 
LVL 47

Assisted Solution

by:for_yan
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);

Open in new window


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

Open in new window

0
 
LVL 92

Assisted Solution

by:objects
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

by:msk_apk
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

by:for_yan
for_yan earned 322 total points
ID: 35186601

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

0
 
LVL 86

Assisted Solution

by:CEHJ
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

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Suggested Solutions

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now