I have such a task: There is the date of manufacture of the goods and the date when it will deteriorate. I need to write such a method so that it determines how many percent the int date has expired. That is, for example, the product was manufactured on January 1, it will deteriorate on January 10 and now on January 5, and the method should return 50:

 private int realWork() { Calendar createDate = new GregorianCalendar(2016, 0, 1); Calendar expirationDate = new GregorianCalendar(2016, 0, 10); Calendar currentDate = Calendar.getInstance(); // предположим 2016 / 0 / 5 long difference = expirationDate.getTimeInMillis() - createDate.getTimeInMillis(); // а что дальше ума не приложу... } 

Here is my problem please help.

    2 answers 2

    Let differenceOne be the difference between the date of manufacture and the expiration date and differenceTwo is the difference between the date of manufacture and the current date.

    Then the desired number is the ratio of differenceTwo to differenceOne (in fractions). If you multiply this ratio by 100, you get the desired percentage.

     private float realWork() { Calendar createDate = new GregorianCalendar(2016, 0, 1); Calendar expirationDate = new GregorianCalendar(2016, 0, 10); Calendar currentDate = new GregorianCalendar(2016, 0, 5); long differenceOne = expirationDate.getTimeInMillis() - createDate.getTimeInMillis(); long differenceTwo = currentDate.getTimeInMillis() - createDate.getTimeInMillis(); return ((float) differenceTwo/differenceOne) * 100; } 

    You only need to round the result.

    • That's cool! How so fast!? - Pavel
    • Thank you very much helped me. - Pavel

    You can try this:

     private static int getPercentRatioForCurrentDay(LocalDate start, LocalDate end) { LocalDate now = LocalDate.now(); if (now.isAfter(end)) return 0; long allDays = ChronoUnit.DAYS.between(start, end); long remainDays = ChronoUnit.DAYS.between(now, end); return (int) (remainDays / (allDays / 100.0)); } 

    The percentage is calculated for the current date.

    • This is some interesting LocalDate class. It's a beautiful decision, but it's still complicated for me ... Thank you very much for the help! - Pavel
    • And how to read ChronoUnit.DAYS.between (start, end) in Russian? And why is the method called on a constant? - Pavel
    • one
      @Pavel this interesting class is a new standard for handling dates and times, starting with Java 8. So, you have to master it, despite the difficulties. In early versions of Java, jodatime is used (under the influence of which new date-time functions were developed in version 8) - Sergey