I am using following function to calculate time difference. It is not showing proper output. After 1 month time difference it is showing 2 minutes difference.
What is wr
I recommend to take a look at Joda Time, noting that:
Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time (JSR-310).
libjoda-time-java
. The jar will be in /usr/share/java
as joda-time.jar
When you use Eclipse, add it to your Java Build path (Project > Properties > Java Build Path > Add External Jar)
import java.sql.Timestamp;
import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;
public class MinimalWorkingExample {
static Date date = new Date(1990, 4, 28, 12, 59);
public static String getTimestampDiff(Timestamp t) {
final DateTime start = new DateTime(date.getTime());
final DateTime end = new DateTime(t);
Period p = new Period(start, end);
PeriodFormatter formatter = new PeriodFormatterBuilder()
.printZeroAlways().minimumPrintedDigits(2).appendYears()
.appendSuffix(" year", " years").appendSeparator(", ")
.appendMonths().appendSuffix(" month", " months")
.appendSeparator(", ").appendDays()
.appendSuffix(" day", " days").appendSeparator(" and ")
.appendHours().appendLiteral(":").appendMinutes()
.appendLiteral(":").appendSeconds().toFormatter();
return p.toString(formatter);
}
public static void main(String[] args) {
String diff = getTimestampDiff(new Timestamp(2013, 3, 20, 7, 51, 0, 0));
System.out.println(diff);
}
}
Output:
22 years, 10 months, 01 day and 18:52:00