Created
November 11, 2013 08:36
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
its also possible to use MessageFormat for plural/singular forms: