Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the time difference between 2 dates in millisec using JodaTime

Tags:

java

jodatime

I'm going to design an application, in which I need to get the exact time difference between two dates. Ex:

Date1:31/05/2011 12:54:00
Date2:31/05/2011 13:54:00

I tried using getTime() but I didn't get exact result.

The expected output for the above inputs is 3600000 (60 * 60 * 1000) millisec but I'm getting 46800000 (13 * 60 * 60 * 1000).

When I went through different java forums people are suggesting to use JodaTime.

Still I'm unable to get the exact result.

The timezone on I'm working is London(GMT).

like image 284
madhu Avatar asked Jul 13 '11 15:07

madhu


People also ask

How to get time difference between two dates in Java?

Parse both start_date and end_date from a string to produce the date, this can be done by using parse() method of the simpleDateFormat class. Find the time difference between two dates in millisecondes by using the method getTime() in Java as d2. getTime() – d1. getTime().

How can you find out the difference between two dates in Java 8?

temporal. ChronoUnit to Find the Difference. The Time API in Java 8 represents a unit of date-time, e.g. seconds or days, using TemporalUnit interface. Each unit provides an implementation for a method named between to calculate the amount of time between two temporal objects in terms of that specific unit.

What is Joda time?

Joda-Time is the most widely used date and time processing library, before the release of Java 8. Its purpose was to offer an intuitive API for processing date and time and also address the design issues that existed in the Java Date/Time API.


1 Answers

Init two dateTime and use Period :

DateTime dt1 = new DateTime(2013,9,11,9,58,56);
DateTime dt2 = new DateTime(2013,9,11,9,58,59);
Period p = new Period(dt1, dt2, PeriodType.millis());

To get difference in milliseconds :

System.out.println(p.getValue(0));
like image 131
skulled Avatar answered Oct 15 '22 07:10

skulled