1
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;


import java.util.Date;
public class DateChal {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        LocalDate start=LocalDate.parse("2018-10-25");
        LocalDate end=LocalDate.parse("2019-10-25");


        Period p=Period.between(start, end);

        System.out.println("Number of days "+p.getDays());

    }

}

o/p:Number of days 0 How to resolve the issue? Please explain what is wrong also?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
SUVAM ROY
  • 103
  • 1
  • 10
  • 4
    There's nothing wrong. It's returning the days field, not the equivalent of the entire period in days. Try `p.getYears()`, and you'll get `1` – ernest_k Oct 11 '18 at 11:38
  • please suggest how to find days between two dates using LocalDate? – SUVAM ROY Oct 11 '18 at 11:40
  • 3
    `ChronoUnit.DAYS.between(start, end)` (returns 365 in your case). – Ole V.V. Oct 11 '18 at 11:40
  • Related: [How to calculate the number of days in a period?](https://stackoverflow.com/questions/30833582/how-to-calculate-the-number-of-days-in-a-period) (Thanks, SHASHI SHEKHAR Barnwal) – Ole V.V. Oct 11 '18 at 11:56

4 Answers4

2

The result period contains 1 year, 0 month and 0 day. You just print the number of days, i.e. 0.

StephaneM
  • 4,779
  • 1
  • 16
  • 33
  • If I don't know in what difference user will input the dates then how to find the days? e.g start:2018-10-15 end:2018-10-25...the code worked fine but not for the above case..what to do then? – SUVAM ROY Oct 11 '18 at 11:48
1

0 is the difference between days. If you print p.getYears() You will see 1.

kaan bobac
  • 729
  • 4
  • 8
0

As already mentioned by soon , Period lists 1 year in your case (P1Y), here you are trying to convert 1 year in number of days since the number of days is 0 it lists 0. How to calculate the number of days in a period?

0
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH);
Date firstDate = sdf.parse("06/30/2017");
Date secondDate = sdf.parse("06/30/2018");

long diffInMillies = Math.abs(secondDate.getTime() - firstDate.getTime());
long diff = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);

System.out.println(diff);
deHaar
  • 17,687
  • 10
  • 38
  • 51