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 wrong with my program?
public String TimestampDiff(Timestamp t) {
long t1 = t.getTime();
String st = null;
long diff;
java.util.Date date = new java.util.Date();
long currT = date.getTime();
System.out.println();
System.out.println(" current timesstamp is " + currT);
diff = (currT - t1) / 60;
int years = (int) Math.floor(diff / (1000 * 60 * 60 * 24 * 365));
double remainder = Math.floor(diff % (1000 * 60 * 60 * 24 * 365));
int days = (int) Math.floor(remainder / (1000 * 60 * 60 * 24));
remainder = Math.floor(remainder % (1000 * 60 * 60 * 24));
int hours = (int) Math.floor(remainder / (1000 * 60 * 60));
remainder = Math.floor(remainder % (1000 * 60 * 60));
int minutes = (int) Math.floor(remainder / (1000 * 60));
remainder = Math.floor(remainder % (1000 * 60));
int seconds = (int) Math.floor(remainder / (1000));
System.out.println("\nyr:Ds:hh:mm:ss " + years + ":" + days + ":"
+ hours + ":" + minutes + ":" + seconds);
if (years == 0 && days == 0 && hours == 0 && minutes == 0) {
st = "few seconds ago";
} else if (years == 0 && days == 0 && hours == 0) {
st = minutes + " minuts ago";
} else if (years == 0 && days == 0) {
st = hours + " hours ago";
} else if (years == 0 && days == 1) {
st = new SimpleDateFormat("'yesterday at' hh:mm a").format(t1);
} else if (years == 0 && days > 1) {
st = new SimpleDateFormat(" MMM d 'at' hh:mm a").format(t1);
} else if (years > 0) {
st = new SimpleDateFormat("MMM d ''yy 'at' hh:mm a").format(t1);
}
st = st.replace("AM", "am").replace("PM", "pm");
return st;
}
Don't cast
long
toint
, cause it will lose its precision. change allint
tolong
, and see the difference.hope this help
I recommend to take a look at Joda Time, noting that:
Installation
libjoda-time-java
. The jar will be in/usr/share/java
asjoda-time.jar
When you use Eclipse, add it to your Java Build path (Project > Properties > Java Build Path > Add External Jar)
Relevant JavaDoc
Example code
Output:
Why I recommend a new solution