Reputation: 766
For startDate and endDate as follows how do I determin the period in Months and days (what is left of it):
String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
SimpleDateFormat format = new SimpleDateFormat(pattern);
Date start = format.parse("2016-11-09T02:00:00.000Z");
Date end = format.parse("2017-09-30T09:00:00.000Z");
As a result I want: 10 Months and 22 Days (end date in)
Upvotes: 0
Views: 1877
Reputation: 6302
This code should work fine for you. This is done using JODA Time. As you tagged this question also with jodatime so I am sure, you will have required packages for jodatime included in your project.
String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
SimpleDateFormat format = new SimpleDateFormat(pattern);
Date start = format.parse("2016-11-09T02:00:00.000Z");
Date end = format.parse("2017-09-30T09:00:00.000Z");
LocalDate a = LocalDate.fromDateFields(start);
LocalDate b = LocalDate.fromDateFields(end);
Period p = new Period(a, b);
System.out.println("Months: "+((p.getYears() * 12) + p.getMonths()));
System.out.println("Days: "+(p.getWeeks()*7+ p.getDays()));
However, if you are using Java 8.0 or above, you can stick with solution suggested by @Anton.
Upvotes: 0
Reputation: 11739
If you can use Java 8
, it is better to use LocalDateTime
and Period
:
ZonedDateTime dateTime = ZonedDateTime.parse("2016-11-09T02:00:00.000Z");
ZonedDateTime end = ZonedDateTime.parse("2017-09-30T09:00:00.000Z");
System.out.println(Period.between(dateTime.toLocalDate(),end.toLocalDate()));
The result is P10M21D
10 Months and 21 Days
Upvotes: 5