How can I calculate the time differences in 24 hour if the user input is 2255 and 2305 the output should be 10 minutes. I got an idea is to separate the input to 2 parts, 2 digits and 2 digits. the first 2 digits is the hour, times it to 60 to make it to minutes. Then plus it with the second 2 digits and then calculate the differences. I dont want use any Date Calendar data type or API to solve it. Thanks
            Asked
            
        
        
            Active
            
        
            Viewed 1.0k times
        
    2
            
            
        - 
                    @user236501 - I rolled back your question, as there was an answer posted. This will allow others with your question to find the answer. ("Sorry please ignore" helps no one) – Mitch Dempsey Sep 28 '10 at 05:54
2 Answers
6
            
            
            String time1 = "2255";
    String time2 = "2305";
    SimpleDateFormat format = new SimpleDateFormat("HHmm");
    Date date1 = format.parse(time1);
    Date date2 = format.parse(time2);
    long difference = date2.getTime() - date1.getTime();        
difference is in millis you can convert it to any unit or you can use DurationFormatUtils from apache-commons to pretty format it.
System.out.println("Duration: "+DurationFormatUtils.formatDuration(difference, "HH:mm"));
apache commons has really nice utility functions, apache-commons (lang)
 
    
    
        sfaiz
        
- 303
- 1
- 8
1
            How to get first 2 digit without using String chartAt.
Highest two digits: number / 100 Lowest two digist: number % 100
But what would you do if user enter 3:05 or 3-05? I think it's problem of usability. Best solution is making UI definitely understandable for user. For example you can use separate fields for hours and minutes.
 
    
    
        Donz
        
- 1,389
- 1
- 13
- 21
- 
                    how about if start time is 0025and endTime is 0035, which mean it is already next day – user236501 Sep 28 '10 at 12:59
- 
                    Do you mean start time is 0035 and end is 0025? So you need to normailze negative result (24 * 60 + (25 - 35)). But if end time is two days before start? As I already said I think it's usability problem. Developer should make controls for input with exact meaning of inputting values. – Donz Sep 28 '10 at 19:56
