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.temporal.* ;
  9. import java.time.format.* ;
  10.  
  11. import java.math.BigDecimal;
  12. import java.math.MathContext;
  13.  
  14. /* Name of the class has to be "Main" only if the class is public. */
  15. class Ideone
  16. {
  17. public static void main (String[] args) throws java.lang.Exception
  18. {
  19.  
  20. //LocalDate start = myResultSet.getObject( … , LocalDate.class ) ; // Retrieve a `LocalDate` from database using JDBC 4.2 and later.
  21. LocalDate start = LocalDate.of( 2018 , Month.JANUARY , 23 );
  22. LocalDate stop = start.plusDays( 101 );
  23.  
  24. Period p = Period.between( start , stop );
  25. long months = p.toTotalMonths();
  26. int days = p.getDays();
  27.  
  28. BigDecimal bdDays = new BigDecimal( days );
  29. BigDecimal bdMaximumDaysInMonth = new BigDecimal( 31 );
  30. BigDecimal fractionalMonth = bdDays.divide( bdMaximumDaysInMonth , MathContext.DECIMAL32 );
  31. BigDecimal bd = new BigDecimal( months ).add( fractionalMonth );
  32.  
  33. double d = bd.round( MathContext.DECIMAL32 ).doubleValue();
  34.  
  35. System.out.println( "From: " + start + " to: " + stop + " = " + bd + " months, using BigDecimal. As a double: " + d );
  36. System.out.println( "p.toString(): " + p );
  37.  
  38.  
  39. }
  40. }
Success #stdin #stdout 0.14s 4575232KB
stdin
Standard input is empty
stdout
From: 2018-01-23 to: 2018-05-04 = 3.3548387 months, using BigDecimal. As a double: 3.354839
p.toString(): P3M11D