Joda time
Instead of rolling the roll yourself, use the Joda-Time library. Joda-Time runs on Android.
The code example below uses Joda-Time 2.4.
Joda-Time uses ISO 8601 standard line formats as the default values for parsing and generating line output. Here you can see the lines DateTime , Interval and Period.
Parse the input string. Notice how we specify the time zone and Locale (to analyze the value of "AM" in English).
String input = "09/10/2014 8:41:26 AM"; DateTimeFormatter formatterInput = DateTimeFormat.forPattern( "MM/dd/yyyy hh:mm:ss a" ).withZoneUTC().withLocale( Locale.ENGLISH ); DateTime then = formatterInput.parseDateTime( input );
Get the current moment. Use this moment to build Interval from now on.
DateTime now = DateTime.now( DateTimeZone.UTC ); Interval interval = new Interval( then , now );
Convert interval to Period , time period defined as the number of days, hours, etc.
Period period = interval.toPeriod();
Create a text view of the Period. This example refers to the default period formatting. Instead, you can create your own formatter using the PeriodFormatterBuilder class.
PeriodFormatter formatterOutput = PeriodFormat.wordBased( Locale.US ); String output = formatterOutput.print( period );
For fun, show a different language. Arbitrary choice of Quebec style.
String outputQuébécois = PeriodFormat.wordBased( Locale.CANADA_FRENCH ).print( period );
Dump for the console.
System.out.println( "input: " + input ); System.out.println( "then: " + then ); System.out.println( "now: " + now ); System.out.println( "interval: " + interval ); System.out.println( "period: " + period ); System.out.println( "output: " + output ); System.out.println( "outputQuébécois: " + outputQuébécois );
At startup.
input: 09/10/2014 8:41:26 AM then: 2014-09-10T08:41:26.000Z now: 2014-10-09T20:44:23.470Z interval: 2014-09-10T08:41:26.000Z/2014-10-09T20:44:23.470Z period: P4W1DT12H2M57.470S output: 4 weeks, 1 day, 12 hours, 2 minutes, 57 seconds and 470 milliseconds outputQuébécois: 4 semaines, 1 jour, 12 heures, 2 minutes, 57 secondes et 470 millisecondes