fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. import java.time.*;
  8. import java.time.format.*;
  9. import java.time.temporal.*;
  10.  
  11. /* Name of the class has to be "Main" only if the class is public. */
  12. class Ideone
  13. {
  14. public static void main (String[] args) throws java.lang.Exception
  15. {
  16.  
  17.  
  18. String inputStart = "2017-01-23 05:25:00".replace ( " " , "T" );
  19. String inputStop = "2018-03-20 07:29:50".replace ( " " , "T" );
  20.  
  21. LocalDateTime start = LocalDateTime.parse ( inputStart );
  22. LocalDateTime stop = LocalDateTime.parse ( inputStop );
  23.  
  24. Period p = Period.between ( start.toLocalDate () , stop.toLocalDate () ).minusDays ( 1 ); // Subtract one, as we account for hours of first day.
  25.  
  26. // Get the Duration of first day's hours-minutes-seconds.
  27. LocalDateTime startNextDay = start.toLocalDate ().plusDays ( 1 ).atStartOfDay ();
  28. Duration dStart = Duration.between ( start , startNextDay );
  29.  
  30. // Get the Duration of first day's hours-minutes-seconds.
  31. LocalDateTime stopStartOfDay = stop.toLocalDate ().atStartOfDay ();
  32. Duration dStop = Duration.between ( stopStartOfDay , stop );
  33.  
  34. // Combine the pair of partial days into a single Duration.
  35. Duration d = dStart.plus ( dStop );
  36.  
  37. System.out.println ( "start/stop: " + start + "/" + stop );
  38. System.out.println ( "p: " + p );
  39. System.out.println ( "dStart: " + dStart + " and dStop: " + dStop );
  40. System.out.println ( "d: " + d );
  41.  
  42. int years = p.getYears ();
  43. int months = p.getMonths ();
  44. int days = p.getDays ();
  45. System.out.println( "Years: " + years + "\nMonths: " + months + "\nDays: " + days );
  46.  
  47. // Enable if in Java 9 or later (but not in Java 8)
  48. // long durationDays = d.toDaysPart();
  49. // long hours = d.toHoursPart();
  50. // long minutes = d.toMinutesPart();
  51. // long seconds = d.toSecondsPart();
  52. // int nanos = d.toNanosPart();
  53.  
  54. }
  55. }
Success #stdin #stdout 0.1s 711680KB
stdin
Standard input is empty
stdout
start/stop: 2017-01-23T05:25/2018-03-20T07:29:50
p: P1Y1M24D
dStart: PT18H35M and dStop: PT7H29M50S
d: PT26H4M50S
Years: 1
Months: 1
Days: 24