2

Basically I've:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

String ActualDate          = "2017-01-05";
LocalDate dt               = LocalDate.parse(ActualDate, formatter);
LocalDateTime currentdate  = LocalDateTime.now();
String datetocheckstr      = currentdate.toString().substring(0, 10);
LocalDate datetochkbetween = LocalDate.parse(datetocheckstr, formatter);
long DAYS                  = ChronoUnit.DAYS.between(datetochkbetween, dt);

This pretty much works and show you the amount of days between the ActualDate and now.

Now I need to convert it to Years, Months, And days. So if My ActualDate = "2015-02-15" and Now It's 2017-03-27 the output I need to get is to be: 2 Years 1 Month and 12 Days.

Peace be upon us all

jaksdfjl
  • 115
  • 3
  • 9

1 Answers1

4

You can use Period class from java 8. I have updated your code. Try it:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    String ActualDate = "2015-02-15";
    LocalDate dt = LocalDate.parse(ActualDate, formatter);
    LocalDate currentdate = LocalDate.now();
    Period period = Period.between(dt, currentdate);
    System.out.println("Years " + period.getYears());  //Years 2
    System.out.println("Months " + period.getMonths()); //Months 1
    System.out.println("Days " + period.getDays()); //Days 11
Roma Khomyshyn
  • 1,112
  • 6
  • 9
  • Thank you so much worked perfect, can you also tell how to do the same thing with `LocalTime`? I'm currently doing it this way `long duration = ChronoUnit.SECONDS.between(now, timetotime);` – jaksdfjl Mar 26 '17 at 12:58
  • You might check this answer http://stackoverflow.com/questions/25747499/java-8-calculate-difference-between-two-localdatetime – Roma Khomyshyn Mar 26 '17 at 13:05
  • Thanks man, this works perfectly and saved me a lot of time! – akmsw Feb 15 '23 at 12:32