0

I have a Duration, like P3M (3 months). How can I get number of days it is from now?

All I have now is this:

Duration.parseWeekBasedPeriod("P3M")

I know the period parameter will never be shorter than 1 week, so parseWeekBasedPeriod() should be ok. But I'm reading JavaDoc, and I can't figure out how to get those days.

I understand, the problem is that months can has 31, 30, 29 and 28 days.

Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126
Pitel
  • 5,334
  • 7
  • 45
  • 72
  • Why use [Time4J](http://www.time4j.net/), when the Java 8+ Time API can do this natively? E.g. `LocalDate today = LocalDate.now(); long days = ChronoUnit.DAYS.between(today, today.plus(Period.parse("P3M")));` – Andreas Apr 02 '20 at 06:57
  • 1
    @Andreas Yes, this special example presented by OP can be done natively, too, in a similar way, but I am sure that the OP also wants other features - maybe around duration - which are not offered by `java.time`. Just compare the APIs, and you will see that [net.time4j.Duration](http://time4j.net/javadoc-en/net/time4j/Duration.html) is more powerful than `java.time.Period`. – Meno Hochschild Apr 02 '20 at 08:40

2 Answers2

2

Using parseWeekBasedPeriod(...) is certainly wrong if you want to apply durations measured in months. This very special method handles week based years which can last either 364 or 371 days (52 or 53 weeks). So I suggest just to use the standard parsing method for calendar-based durations. The following code also strongly simplifies the evaluation of days between two dates (see last line).

Duration<CalendarUnit> duration = Duration.parseCalendarPeriod("P3M");
PlainDate today = PlainDate.nowInSystemTime();
PlainDate later = today.plus(duration);
long days = CalendarUnit.DAYS.between(today, later);

By the way, I have tested the method for weekbased durations once again. It will usually throw an exception if it tries to parse months. You didn't seem to have seen any exception so I assume that the fact that you use untyped constructs like "val" has shadowed the necessary type information in processing the duration string (and Time4J is a strongly typed library). Hence - if technically possible for you -, I strongly recommend to use type-safe code as shown in my solution.

Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126
1

Finaly figured it out:

val period = Duration.parseWeekBasedPeriod("P3M")
val start = PlainDate.nowInSystemTime()
val end = start.plus(period)
val days: Long = Duration.`in`(CalendarUnit.DAYS).between(start, end).getPartialAmount(CalendarUnit.DAYS)
Pitel
  • 5,334
  • 7
  • 45
  • 72