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 ldtStart = LocalDateTime.parse ( inputStart ); // LocalDateTime used only briefly here, to parse inputs. Then we switch to `ZonedDateTime`.
  22. LocalDateTime ldtStop = LocalDateTime.parse ( inputStop );
  23.  
  24. ZoneId z = ZoneId.of( "America/Montreal" );
  25. ZonedDateTime zdtStart = ldtStart.atZone( z ); // Invalid values may be adjusted, such as during the hour of a "Spring-forward" Daylight Saving Time (DST) switch-over.
  26. ZonedDateTime zdtStop = ldtStop.atZone( z );
  27.  
  28. Period p = Period.between ( zdtStart.toLocalDate () , zdtStop.toLocalDate () ).minusDays ( 1 ); // Subtract one, as we account for hours of first day.
  29.  
  30. // Get the Duration of first day's hours-minutes-seconds.
  31. ZonedDateTime zdtStartNextDay = zdtStart.toLocalDate ().plusDays ( 1 ).atStartOfDay ( z );
  32. Duration dStart = Duration.between ( zdtStart , zdtStartNextDay );
  33.  
  34. // Get the Duration of first day's hours-minutes-seconds.
  35. ZonedDateTime zdtStopStartOfDay = zdtStop.toLocalDate ().atStartOfDay ( z );
  36. Duration dStop = Duration.between ( zdtStopStartOfDay , zdtStop );
  37.  
  38. // Combine the pair of partial days into a single Duration.
  39. Duration d = dStart.plus ( dStop );
  40.  
  41. System.out.println ( "zdtStart: " + zdtStart );
  42. System.out.println ( "zdtStop: " + zdtStop );
  43. System.out.println ( "p: " + p );
  44. System.out.println ( "dStart: " + dStart + " and dStop: " + dStop );
  45. System.out.println ( "d: " + d );
  46.  
  47. int years = p.getYears ();
  48. int months = p.getMonths ();
  49. int days = p.getDays ();
  50. System.out.println( "Years: " + years + "\nMonths: " + months + "\nDays: " + days );
  51.  
  52. // Enable if in Java 9 or later (but not in Java 8)
  53. // long durationDays = d.toDaysPart();
  54. // long hours = d.toHoursPart();
  55. // long minutes = d.toMinutesPart();
  56. // long seconds = d.toSecondsPart();
  57. // int nanos = d.toNanosPart();
  58.  
  59. }
  60. }
Success #stdin #stdout 0.11s 712192KB
stdin
Standard input is empty
stdout
zdtStart: 2017-01-23T05:25-05:00[America/Montreal]
zdtStop: 2018-03-20T07:29:50-04:00[America/Montreal]
p: P1Y1M24D
dStart: PT18H35M and dStop: PT7H29M50S
d: PT26H4M50S
Years: 1
Months: 1
Days: 24