Joda time, Period to total millis

后端 未结 3 924
遇见更好的自我
遇见更好的自我 2021-02-18 15:00

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 fi

3条回答
  •  南方客
    南方客 (楼主)
    2021-02-18 15:57

    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.

提交回复
热议问题