How to set 2 dates and see how much time has passed between them.

For example:

01.01.2000 10:10:10 02.03.2005 20:10:20 

and get back: 1 день 2 месяца 5 лет 10 часов 0 минут 10 секунд

And then you need to sort from the biggest time to the smallest.
I am writing in Java 7.

    2 answers 2

    This is easy to do with org.joda.time.Period

     private static String strDiff(DateTime from, DateTime to) { Period period = new Period(from, to, PeriodType.yearMonthDayTime()); return period.getYears() + "y " + period.getMonths() + "m " + period.getDays() + "d " + period.getHours() + "h " + period.getMinutes() + "min " + period.getSeconds() + "s" + ""; } public static void main(String[] args) { DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); DateTime start = formatter.parseDateTime("2017-04-03 03:00:00"); DateTime end = formatter.parseDateTime("2017-04-11 03:00:00"); System.out.println(strDiff(start, end)); } 

      Create two dates, then take time from them in milliseconds and find out the difference. Then parse.

      • Why minus something? The answer is true because ... - Barmaley
      • one
        @Barmaley, Not minus, but the answer is incorrect. The same number of milliseconds at different times can mean different periods. The task of parsing the number of months is especially ambiguous ... - vp_arth