6

I have time data split in two strings - one string for date, and one for time.
I want to calculate the diff. of such two times in Java.
e.g.

  • time 1:"26/02/2011" and "11:00 AM"
  • time 2:"27/02/2011" and "12:15 AM"

Difference would be like 13 hours 15 minutes.

user594720
  • 449
  • 3
  • 9
  • 18

6 Answers6

11
String str_date1 = "26/02/2011";
String str_time1 = "11:00 AM";

String str_date2 = "27/02/2011";
String str_time2 = "12:15 AM" ;

DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm a");
Date date1 = formatter.parse(str_date1 + " " + str_time1);
Date date2 = formatter.parse(str_date2 + " " + str_time2);

// Get msec from each, and subtract.
long diff = date2.getTime() - date1.getTime();

System.out.println("Difference In Days: " + (diff / (1000 * 60 * 60 * 24)));

Obs: This is only valid as an aproximation. See Losing Time on the Garden Path.)

tiago2014
  • 3,392
  • 1
  • 21
  • 28
8
try {
    String date1 = "26/02/2011";
    String time1 = "11:00 AM";
    String date2 = "27/02/2011";
    String time2 = "12:15 AM";

    String format = "dd/MM/yyyy hh:mm a";

    SimpleDateFormat sdf = new SimpleDateFormat(format);

    Date dateObj1 = sdf.parse(date1 + " " + time1);
    Date dateObj2 = sdf.parse(date2 + " " + time2);
    System.out.println(dateObj1);
    System.out.println(dateObj2);

    long diff = dateObj2.getTime() - dateObj1.getTime();
    double diffInHours = diff / ((double) 1000 * 60 * 60);
    System.out.println(diffInHours);
    System.out.println("Hours " + (int)diffInHours);
    System.out.println("Minutes " + (diffInHours - (int)diffInHours)*60 );

} catch (ParseException e) {
    e.printStackTrace();
}

output

Sat Feb 26 11:00:00 EST 2011
Sun Feb 27 00:15:00 EST 2011
13.25
Hours 13
Minutes 15.0
Bala R
  • 107,317
  • 23
  • 199
  • 210
1

tl;dr

Duration.between(
    ZonedDateTime.of(
        LocalDate.parse( "26/02/2011" , DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ) ,
        LocalTime.parse( "11:00 AM" , DateTimeFormatter.ofPattern( "hh:mm a" ) ) ,
        ZoneId.of( "America/Montreal" )
    )
    ,
    ZonedDateTime.of(
        LocalDate.parse( "27/02/2011" , DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ) ,
        LocalTime.parse( "12:15 AM" , DateTimeFormatter.ofPattern( "hh:mm a" ) ) ,
        ZoneId.of( "America/Montreal" )
    )
).toString()

See live code in IdeOne.com.

Time zone

The Question and the other Answers all ignore the crucial issue of time zone. You cannot calculate elapsed time between two date-time strings without knowing the intended time zone. For example, in places with Daylight Saving Time (DST), on the night of the cut-over, a day may be 23 hours long or 25 hours long rather than 24 hours long.

java.time

The modern way to do date-time work is with the java.time classes. These supplant the troublesome old date-time classes such as java.util.Date and java.util.Calendar.

Local…

First parse the input strings. These lack any indication of time zone, so we parse them as Local… types.

Define a DateTimeFormatter to match your string inputs. By the way, in the future, use standard ISO 8601 formats when serializing date-time values to text.

DateTimeFormatter df = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate ld = LocalDate.parse( "26/02/2011" , df ) ;

ld.toString(): 2011-02-2011

DateTimeFormatter tf = DateTimeFormatter.ofPattern( "hh:mm a" );
LocalTime lt = LocalTime.parse( "11:00 AM" , tf ) ;

lt.toString(): 11:00:00

ZoneId

You need to know the time zone intended by your business scenario. I will arbitrarily choose one.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" );

ZonedDateTime

Apply the zone to get a ZonedDateTime.

ZonedDateTime zdtStart = ZonedDateTime.of( ld , lt , z );

zdtStart.toString(): 2011-02-26T11:00:00-05:00[America/Montreal]

Duration

Do the same to get a zdtStop. Calculate the elapsed time as a span of time not attached to the timeline, in a Duration.

Duration d = Duration.between( zdtStart , zdtStop );

Call toString to generate a String in standard ISO 8601 format for durations: PnYnMnDTnHnMnS. The P marks the beginning while the T separates the two portions.

String output = d.toString();

d.toString(): PT13H15M

In Java 9 and later, call the to…Part methods to access each component.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

  • Java SE 8 and SE 9 and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • The statement "The Question and the other Answers all ignore the crucial issue of time zone" is not quite true. The answer of @Bala R does take the system timezone into account (implicitly) and can correctly display the result on quasi UTC-timeline in hours and minutes. – Meno Hochschild Dec 08 '16 at 10:47
1

Have a look at DateFormat, you can use it to parse your strings with the parse(String source) method and the you can easily manipulate the two Dates object to obtain what you want.

DateFormat df = DateFormat.getInstance();
Date date1 = df.parse(string1);
Date date2 = df.parse(string2);
long difference = date1.getTime() - date2.getTime();
Date myDate = new Date(difference);

The to show the Date :

String diff = df.format(myDate);
krtek
  • 26,334
  • 5
  • 56
  • 84
1

You need to first convert the strings to java.util.Date objects (using SimpleDateFormat.parse(String) for instance). Then you can use Date.getTime() for each of the two Date instances that you parsed and compute the difference in milliseconds or make use of a java.util.Calendar or the joda time API for advanced computations.

Costi Ciudatu
  • 37,042
  • 7
  • 56
  • 92
  • it is fine but how can i make a single date object with two strings? – user594720 Feb 27 '11 at 10:31
  • You can't. You'll end up with two Date objects that you will than compare. Let me edit the answer to make it more clear. – Costi Ciudatu Feb 27 '11 at 10:34
  • i know that i have to compare two different objects but i am asking how to put time and date in a single object? – user594720 Feb 27 '11 at 10:36
  • You will need to concatenate those two strings and use a format pattern like this: `yyyy-MM-dd hh:mm`. Have a look at the `SimpleDateFormat` javadoc. tiagoinu's answer bellow contains a concrete example of this. – Costi Ciudatu Feb 27 '11 at 10:38
0

try this one

you can calculate days,hours and minutes

public class TimeUtils {

public static final String HOURS = "hours";
public static final String MINUTES = "minutes";
public static final String DAYS = "days";

 public static int findTheNumberBetween(String type, Date day1, Date day2) {

    long diff = day2.getTime() - day1.getTime();
    switch (type) {
        case DAYS:
            return (int) TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
        case HOURS:
            return (int) TimeUnit.HOURS.convert(diff, TimeUnit.MILLISECONDS);
        case MINUTES:
            return (int) TimeUnit.MINUTES.convert(diff, TimeUnit.MILLISECONDS);
    }
    return 0;
}
}

and the use it like

  Date day1= TimeUtils.getDateTime("2016-12-08 02:06:14");
    Date day2 = TimeUtils.getDateTime("2016-12-08 02:10:14");

    Log.d(TAG, "The difference: "+TimeUtils.findTheNumberBetween(TimeUtils.MINUTES,day1,day2));
Ameen Maheen
  • 2,719
  • 1
  • 28
  • 28