Joda-Time all in minutes

你。 提交于 2019-12-07 22:46:39

问题


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.


回答1:


Since Periods are defined by individual component fields (e.g. 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 Durations from the start (if possible) and not using Periods at all.




回答2:


Yes, you can easily get minutes from a Joda-Time Period object.

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



回答3:


You can try (double) period.getMillis()/60000 and reformat it.



来源:https://stackoverflow.com/questions/8793475/joda-time-all-in-minutes

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