0

I want to get the difference in seconds between end_date_time and system_date_time using JAVA, for example:

if 
    end_date_time = 2015-02-21 13:00:00
    system_date_time = 2015-02-20 13:00:00
then 
    difference = 86400

Please tell how can I do this?

Raees Khan
  • 371
  • 1
  • 5
  • 20
  • 3
    Really? None of the 65,812 hits when entering `java datetime difference site:stackoverflow.com` into Google were any good? If not, why would you expect the 65,813th to be any different? :-) – paxdiablo Feb 19 '15 at 00:26
  • 2
    possible duplicate of [Calculating the Difference Between Two Java Date Instances](http://stackoverflow.com/questions/1555262/calculating-the-difference-between-two-java-date-instances) – Samuel Edwin Ward Feb 19 '15 at 00:30

1 Answers1

0

If you have a Date type already, it's as simple as:

(System.currentTimeMillis() - myDate.getTime()) / 1000;

If you have a string and need to convert it to a date, you use a SimpleDateFormat instance:

String dateString = "2015-02-21 13:00:00" // end_date_time
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
Date myDate = sdf.parse(dateString);

If you're using Java8, this is much easier:

String dateString = "2007-12-03T10:15:30.00Z";
Instant.now().until(Instant.parse(dateString), ChronoUnit.SECONDS);

Your dateString must be parseable in the ISO format, though:

"yyyy-mm-ddThh:mm:ss.SZ"
Steve K
  • 4,863
  • 2
  • 32
  • 41
  • No not never. This doesn't account for drifts in dates cause by leap seconds, leap years, century and millennium boundaries. Use appropriate libraries, like JodaTime or java 8s new time API – MadProgrammer Feb 19 '15 at 02:24
  • You're correct. Added a reference to the Java8 method. – Steve K Feb 19 '15 at 03:23