Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 684
  • Last Modified:

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.
0
OliviaRedhorse
Asked:
OliviaRedhorse
  • 12
  • 9
  • 3
  • +2
14 Solutions
 
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
0
 
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
0
 
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();
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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


0
 
for_yanCommented:
If you just use this pattern ("HH:mm:ss.SSS") I don't think SimpleDateFormat will require date
0
 
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

0
 
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

0
 
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

0
 
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

0
 
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.
0
 
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?
0
 
for_yanCommented:

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

Open in new window

0
 
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







0
 
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




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

Open in new window

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

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

Open in new window

0
 
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

0
 
objectsCommented:
> 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
 
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.

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

0
 
CEHJCommented:
If it were not important, then new Date(0L) would give you the reference time. Most often it won't
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 12
  • 9
  • 3
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now