0

How do I convert given days into Calendar format in java.

Example Initial date is 01-01-2015. Given days are 125 days. This should be converted as 0 years, 4 months, 5 days and added to initial date which would become 06-05-2015.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
javalearner
  • 347
  • 2
  • 7
  • 21
  • From above solution, you can get number of years, months, days to be added. Use Calendar object to add these values in your initial date. If you want you can add extra condition for leap year. – Sanchit Khera Dec 15 '16 at 07:13
  • how to add condition for leap year ? and some month contains 30 and 31 days..how to handle this suituation...can you plz be little elaborative – javalearner Dec 15 '16 at 07:18
  • For leap year, you can check if any year between your initial date and final date is a leap year(s), add 1 day to final date for each leap year in between. To check leap year just year%4 will do. – Sanchit Khera Dec 15 '16 at 07:21
  • ok..got it..how about 30 and 31 days for some months.. – javalearner Dec 15 '16 at 07:25
  • 1
    " this should be converted as 0years,4 months,5 days" -- no, it shouldn't. You should add days directly to the date, using a good API. Preferably the java.time API, see the suggested duplicatie. 125 days is not for 4 months and 5 days, that completely depends on the day from which you start, as months don't have equal lengths. – Erwin Bolwidt Dec 15 '16 at 07:28
  • @ErwinBolwidt...right..any API which can do that job...? – javalearner Dec 15 '16 at 07:31

1 Answers1

4

You can use Period class from java8's new java.time API to convert the difference between two dates into years, months and days:

LocalDate initial = LocalDate.of(2015, 1, 1);

LocalDate end = initial.plusDays(125); 

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

int years = p.getYears();   // 0
int months = p.getMonths(); // 4 
int days = p.getDays();     // 5
Misha
  • 27,433
  • 6
  • 62
  • 78