Joda time, Period to total millis

隐身守侯 提交于 2019-12-22 01:33:39

问题


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.)


回答1:


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.




回答2:


If you want to get the millis from a specific time it can be done by using the plus() or minus() methods of the DateTime class.

e.g. getting the millis from now

 DateTime start = new DateTime();  //NOW
 DateTime end = start.plus(<your period>);
 long millis = end.getMillis() - start.getMillis();



回答3:


Using Joda time 2.3, it is:

toStandardDuration().getMillis()


来源:https://stackoverflow.com/questions/9625306/joda-time-period-to-total-millis

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!