1

For example i have two dates:

2018-11-30 18:00:00
2018-12-01 00:00:00

How you can see, that less then 24 hours difference, but I need to recognize that a one day of differnce, and i can't just subtract, cause of month change. In output i need to return int count of days.

In c# it will be just:

(EndDate - StartDate).TotalDays

What Java code will be similar?

I searched somewhere before I asked, but that didn’t solve the problem. Here’s my attempt after searching:

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime d1 = LocalDateTime.parse("2018-11-30 18:00:00", dtf);
LocalDateTime d2 = LocalDateTime.parse("2018-12-01 00:00:00", dtf);
long days = ChronoUnit.DAYS.between(d1, d2);
System.out.println("Days: " + days); // Days: 0

I wish to get 1 day of difference.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
arkhamvm
  • 619
  • 1
  • 15
  • 29
  • 1
    `ChronoUnit.DAYS.between(startDateTime.toLocalDate(), endDateTime.toLocalDate())`. If you are serious about getting an `int`, not a `long`, pass through `Math.toIntExact()`. – Ole V.V. Dec 27 '18 at 09:13
  • In case I didn’t find the best original questions and answers for you, please just continue searching, they are out there for sure. – Ole V.V. Dec 27 '18 at 09:23
  • Thanks for answer, i search somewhere before ask, but problem doesn't solved: ``` DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime d1 = LocalDateTime.parse("2018-11-30 18:00:00", dtf); LocalDateTime d2 = LocalDateTime.parse("2018-12-01 00:00:00", dtf); long days = ChronoUnit.DAYS.between(d1, d2); System.out.println("Days: " + days); // Days: 0 ``` I wish to get 1 day of difference. – arkhamvm Dec 28 '18 at 04:28
  • Really nice attempt, and really close. Just convert to `LocalDate` as in my first comment: `ChronoUnit.DAYS.between(d1.toLocalDate(), d2.toLocalDate())`. This will give 1 day (I have tried it). PS I upvoted your question after you have now provided MCVE with desired and observed result. – Ole V.V. Dec 28 '18 at 07:13
  • Oh *facepalm* shame on me. Thank you, LocalDates works as expected. – arkhamvm Dec 29 '18 at 09:27

0 Answers0