Joda-Time只需数分钟 [英] Joda-Time all in minutes
问题描述
是否有隐藏的方法来获取以分钟为单位的 Joda-Time 时间段(或任何时间)其他)
Is there a hidden way to get a Joda-Time period in minutes (or any other)
现在我要做:
(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.
我的时间将是最大小时,并且永远不会是几天.这是我第一次在Joda-Time工作.
My times will be max hours, and will never be days. This is my first time with Joda-Time.
推荐答案
由于Period
由各个组成部分字段定义(例如5年7周),因此无法(轻松地)将它们直接转换为分钟值,而无需先将它们与特定的时间关联.
Since Period
s 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.
例如,如果您有2个月的时间,那么它包含多少分钟?为了知道这一点,您需要知道哪两个月.也许:
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:
- 六月和七月? (30 + 31 = 61天)
- 七月和八月? (31 + 31 = 62天)
- a年2月和3月? (29 + 31 = 60天)
其中每一个都有不同的分钟数.
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:
If you're guaranteed that your
Period
won't contain months (or higher), you can just usetoStandardSeconds()
:
Period period = new Period(60, 40, 20, 500);
System.out.println(period.toStandardSeconds().getSeconds() / 60.0);
// outputs 3640.3333333333335
但是,如果您的Period
最终以一个月的值结尾,那么您将获得(根据Javadoc)一个UnsupportedOperationException
:
However, if you do end up with a month value in your Period
, you'll get (per the javadoc) an UnsupportedOperationException
:
java.lang.UnsupportedOperationException:无法转换为秒,因为此时间段包含的长度和月份各不相同
java.lang.UnsupportedOperationException: Cannot convert to Seconds as this period contains months and months vary in length
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")
请注意,#2将根据代码运行的日期打印不同的值.但这仅仅是它的本质.
Note that #2 will print different values depending on the day the code runs. But that's just the nature of it.
或者,您可以考虑从一开始就使用Duration
(如果可能的话),而根本不使用Period
.
As an alternative, you might consider just using Duration
s from the start (if possible) and not using Period
s at all.
这篇关于Joda-Time只需数分钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!