简体   繁体   中英

Joda-Time all in minutes

Is there a hidden way to get a Joda-Time period in minutes (or any other)

Right now I do:

(period.getHours()*60 + period.getMinutes() + roundTwoDecimals((double)(period.getSeconds()/60)))
double roundTwoDecimals(double d) {
        DecimalFormat twoDForm = new DecimalFormat("#.##");
    return Double.valueOf(twoDForm.format(d));
}

But for some reason I think there could be an easier way.

EDIT: My times will be max hours, and will never be days. This is my first time with Joda-Time.

Since Period s are defined by individual component fields (eg 5 years, 7 weeks), they cannot (easily) be converted directly to, say, minute values without first associating them with a particular instant in time.

For example, if you have a period of 2 months, how many minutes does it contain? In order to know that, you need to know which two months. Perhaps:

  • June and July? (30 + 31 = 61 days)
  • July and August? (31 + 31 = 62 days)
  • February of a leap year and March? (29 + 31 = 60 days)

Each one of those is going to have a different number of minutes.

That in mind, there are a few ways to approach this. Here are a couple:

  1. If you're guaranteed that your Period won't contain months (or higher), you can just use toStandardSeconds() :

     Period period = new Period(60, 40, 20, 500); System.out.println(period.toStandardSeconds().getSeconds() / 60.0); // outputs 3640.3333333333335 

    However, if you do end up with a month value in your Period , you'll get (per the javadoc) an UnsupportedOperationException :

    java.lang.UnsupportedOperationException: Cannot convert to Seconds as this period contains months and months vary in length

  2. Otherwise, you can associate the Period with an instant in time and use a Duration :

     Period period = new Period(1, 6, 2, 2, 5, 4, 3, 100); // apply the period starting right now Duration duration = period.toDurationFrom(new DateTime()); System.out.println(duration.toStandardSeconds().getSeconds() / 60.0); // outputs 810964.05 (when right now is "2012-01-09T13:36:43.880-06:00") 

Note that #2 will print different values depending on the day the code runs. But that's just the nature of it.

As an alternative, you might consider just using Duration s from the start (if possible) and not using Period s at all.

是的,您可以轻松地从Joda-Time Period对象获取分钟数。

int minutes = Minutes.standardMinutesIn( period ).getMinutes();

您可以尝试(double) period.getMillis()/60000并重新格式化它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM