Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get ceil value in Duration

I have Duration object which I want to return full duration in days (rounded up), so for:

  1. 1m - 1d
  2. 1d - 1d
  3. 1d1h - 2d
  4. 1d1m - 2d

Unfortunately toDays() method is returning only full days. Is there any method for getting ceil value?

like image 614
ByeBye Avatar asked Oct 22 '25 21:10

ByeBye


1 Answers

The way you can do a ceil with integer division is to add 1 less than the denominator:

(numerator + denominator - 1) / denominator

So, do the same here: add 1 nanosecond less than 1 day to your duration, and then use toDays().

duration.plusDays(1).minusNanos(1).toDays()

Looking in the docs, it suggests that toDays() might only consider to second precision. However, this little demo shows that it works to nanosecond precision (at least for non-negative durations).

like image 199
Andy Turner Avatar answered Oct 24 '25 12:10

Andy Turner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!