Skip to content

Instantly share code, notes, and snippets.

@dzhibas
Created November 11, 2013 08:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dzhibas/7409838 to your computer and use it in GitHub Desktop.
Save dzhibas/7409838 to your computer and use it in GitHub Desktop.
date diff in java for android app test NOTE: months begins with 0 in calendar
import static java.lang.System.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
class DateTest
{
public void test()
{
TimeUnit timeUnit = TimeUnit.SECONDS;
Calendar cal1 = Calendar.getInstance();
Date d = cal1.getTime();
out.println(d.toString());
Calendar cal2 = Calendar.getInstance();
cal2.set(2013, 9-1, 23);
Date d2 = cal2.getTime();
long dl = d.getTime();
long dl2 = d2.getTime();
long diffInMillies = dl-dl2;
long s = timeUnit.convert(diffInMillies, TimeUnit.MILLISECONDS);
long years = s / (60 * 60 * 24 * 365);
long restYears = s - (years * 60 * 60 * 24 * 365);
long months = restYears / (24 * 60 * 60 * 30);
long restMonths = restYears - (months * 24 * 60 * 60 * 30);
long weeks = restMonths / (24 * 60 * 60 * 7);
long restWeeks = restMonths - (weeks * 24 * 60 * 60 * 7);
long days = restWeeks / (24 * 60 * 60);
String dates = "";
if (years > 0) {
dates += years + " year";
if (years == 1)
dates += " ";
else
dates += "s ";
}
if (months > 0) {
dates += months + " month";
if (months == 1)
dates += " ";
else
dates += "s ";
}
if (weeks > 0) {
dates += weeks + " week";
if (weeks == 1)
dates += " ";
else
dates += "s ";
}
dates += days + " day";
if (days > 1) {
dates += "s";
}
dates += " old";
out.println( dates );
}
public static void main(String[] args)
{
DateTest d = new DateTest();
d.test();
}
}
@dzhibas
Copy link
Author

dzhibas commented Nov 11, 2013

its also possible to use MessageFormat for plural/singular forms:

String formatString = "there were {0} {0,choice,0#objects|1#object|1<objects}";
MessageFormat fmt = new MessageFormat(formatString);
fmt.format(new Object[] { new Long(numberOfObjects) });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment