I am given two dates (one of which is the present) and need to find the difference between the two. My code is giving me bad output (sometimes even negative).
I have tried using the Months, Days, Seconds, Hours, and Years classes and appropriate between methods with no luck.
Edit: Went back to my original code but without Duration. @Basil Bourque posted a great solution but I just don't have enough experience with Periods/Duration and all that to format dynamically from them.
Solution
public static String formattedTime(DateTime d){
DateTime present = new DateTime(Calendar.getInstance());
//dont really want to deal with WHY its 7hrs ahead. o well
DateTime date = d.minusHours(7);
int diff = Seconds.secondsBetween(date,present).getSeconds();
String postfix = "s";
Log.i("time", "" + diff);
if(diff>59){
diff = Minutes.minutesBetween(date, present).getMinutes();
postfix = "s";
if(diff>59){
diff = Hours.hoursBetween(date, present).getHours();
postfix = "hr";
if(diff>1)
postfix+="s";
if(diff>23){
diff = Days.daysBetween(date, present).getDays();
postfix = "d";
if(diff>6){
diff = Weeks.weeksBetween(date, present).getWeeks();
postfix = "wk";
if(diff>1)
postfix+="s";
if(diff>3){
diff = Months.monthsBetween(date, present).getMonths();
postfix = "m";
if(diff>11){
diff = Years.yearsBetween(date, present).getYears();
postfix = "yr";
if(diff>1)
postfix+="s";
}
}
}
}
}
}
return diff+postfix;
}