我在 Android Studio 项目中使用 joda-time-2.5。
我无法弄清楚我缺少什么来正确格式化具有年份和/或月份的字符串。
周期计算正确 - 但不会超过“周”,例如。 1000000 分钟正确格式为“99wks, 1day, 10hrs + 40mins”。但不是月/年格式,例如。 “1 年、10 个月、3 周、1 天、10 小时 + 40 分钟”等
我尝试过各种变体
Period pA = new Period(mA);
Period pA = new Period(mA, PeriodType.standard());
Period pA = new Period(mA, PeriodType.yearMonthDay());
等等,但这些没有什么区别。
我尝试添加/删除各种 .appends/years/months/printZero
- 这没有什么区别。
我尝试更改周期单位:如果我使用月或年,它会起作用,例如
Months mA = Months.months(15);
Period pA = new Period(mA, PeriodType.standard());
正确生成“1year, 3months”。
我知道“年”和“月”并不精确(在这种情况下,近似值实际上就可以了),但我认为这就是 periodTypes/yearMonthDay 或标准所处理的?
我也尝试过 PeriodFormat.getDefault().print(period)
但没有成功。
请查找下面的代码:
private String formatTimeStr(int minutes){
Minutes mA = Minutes.minutes(minutes);
Period pA = new Period(mA);
PeriodFormatter dhm = new PeriodFormatterBuilder()
.printZeroNever()
.appendYears()
.appendSuffix("year","years")
.appendSeparator(", ")
.appendMonths()
.appendSuffix("mnth", "mnths")
.appendSeparator(", ")
.appendWeeks()
.appendSuffix("wk", "wks")
.appendSeparator(", ")
.appendDays()
.appendSuffix("day", "days")
.appendSeparator(", ")
.appendHours()
.appendSuffix("hr", "hrs")
.appendSeparator(" & ")
.appendMinutes()
.appendSuffix("min", "mins")
.toFormatter();
String formattedTimeStr = dhm.print(pA.normalizedStandard());
return formattedTimeStr;
}
最佳答案
事实上,正如您已经认识到的那样,严格意义上来说,分钟不能转换为月份。 Joda-Time-documentation也说出来了。
If the period contains years or months, then the months will be normalized to be between 0 and 11. The days field and below will be normalized as necessary, however this will not overflow into the months field. Thus a period of 1 year 15 months will normalize to 2 years 3 months. But a period of 1 month 40 days will remain as 1 month 40 days.
从技术上讲,有两种转换选项。
a) 您定义一个引用时间戳。然后你可以执行以下操作:
LocalDateTime tsp1 = new LocalDateTime(); // now as example
LocalDateTime tsp2 = tsp1.plusMinutes(minutes);
Period p = new Period(tsp1, tsp2, PeriodType.standard()); // or other period type?
b) 您找到并开发了一种基于时间单位的估计长度的舍入算法。例如,您可能愿意接受 30.5 天或类似的四舍五入的月份长度。如果用例不需要绝对精度,那么这可以被认为是公平的解决方案,因为这在社交媒体场景中通常是正确的。据我所知,Joda-Time 不支持这种开箱即用的舍入功能(与其他库相比)。
关于java - Joda 时间 - 无法以分钟为单位计算月/年,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28148854/