Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joda time, Period to total millis

Tags:

I'm trying to get the total amount of Milliseconds (not the millis field) from the Period object instance. I've tried multiple conversions, as I couldn't find any method easily giving it.

Has anyone ever needed that and managed to retrieve it ?

(I need this for my patch, to figure out a negative period; negative millis = negative period.)

like image 638
Dror Weiss Avatar asked Mar 08 '12 21:03

Dror Weiss


People also ask

What is Joda-Time format?

Joda-Time provides a comprehensive formatting system. There are two layers: High level - pre-packaged constant formatters. Mid level - pattern-based, like SimpleDateFormat. Low level - builder.

Does Joda datetime have time zones?

An interval in Joda-Time represents an interval of time from one instant to another instant. Both instants are fully specified instants in the datetime continuum, complete with time zone.

What is Joda-Time API?

Joda-Time is an API created by joda.org which offers better classes and having efficient methods to handle date and time than classes from java. util package like Calendar, Gregorian Calendar, Date, etc. This API is included in Java 8.0 with the java. time package.


1 Answers

You can't get the millis directly from a Period, since fields like months and years are variable in terms of milliseconds.

In order to make this work, you need to supply a "baseline" instant from which Period can calculate that actual millisecond duration.

For example, the Period.toDurationFrom and Period.toDurationTo methods take such a baseline instant, and calculate a Duration object, which you can then obtain the millis.

The Javadoc for toDurationFrom says:

Gets the total millisecond duration of this period relative to a start instant. This method adds the period to the specified instant in order to calculate the duration.

An instant must be supplied as the duration of a period varies. For example, a period of 1 month could vary between the equivalent of 28 and 31 days in milliseconds due to different length months. Similarly, a day can vary at Daylight Savings cutover, typically between 23 and 25 hours.

So you need to pick an appropriate baseline instant for your application.

like image 128
skaffman Avatar answered Jan 03 '23 02:01

skaffman