1

I've two following dates

String d1 = "Fri May 11 01:48:50 +0000 2015";

String d2 = "Thu May 10 20:49:20 +0000 2015";

long result = 0;

I want to subtract d2 from d1. But, I don't know how to format d1 and d2(SimpleDateFormat or something else) for subtraction. Could someone help me?

Kenny
  • 19
  • 4

1 Answers1

2

In Java 8+, you can get the java.time.Duration between two Date(s) with something like

String d1 = "Fri May 11 01:48:50 +0000 2015";
String d2 = "Thu May 10 20:49:20 +0000 2015";
DateFormat df = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy");
try {
    Date a = df.parse(d1);
    Date b = df.parse(d2);
    Duration d = Duration.between(a.toInstant(), b.toInstant());
    System.out.println(d);
} catch (Exception e) {
    e.printStackTrace();
}

Which outputs

PT-4H-59M-30S

For 4 hours, 59 minutes and 30 seconds.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249