我正在制作Android应用,我需要计算一段时间(小时和分钟)的总和。实际上,我建立了一个方法来实现这个目标,但我在负面时期遇到了问题。
例如:
第一种情况 - >是正确的
Input 1: 3:00
Input 2: 0:30
Output: 3:30 // This is correct --> 3:00 + 0:30 = 3:30
第二种情况 - >是错的
Input 1: 3:00
Input 2: -0:30
Output: 3:30 // This is wrong...
Output Expected: 2:30 // --> 3:00 + (-0:30) = 2:30
这是我的代码:
public String OperationsHH_Sum(String time1, String time2)
{
PeriodFormatterBuilder builder = new PeriodFormatterBuilder();
builder.minimumPrintedDigits(2);
builder.printZeroAlways();
builder.appendHours();
builder.appendLiteral(":");
builder.appendMinutes();
PeriodFormatter pf = builder.toFormatter();
Period period1 = pf.parsePeriod(time1);
Period period2 = pf.parsePeriod(time2);
Period normalized;
Period total;
total = period1.plus(period2);
normalized = total.normalizedStandard(PeriodType.time());
return pf.print(normalized);
}
我做错了什么?
谢谢!
修改
我解决了我的问题......这是代码:
public String OperationsHH_Sum(String time1, String time2)
{
String[] time1_out, time2_out;
if (time1.contains("-"))
{
time1_out = time1.split(":");
time1_out[1] = "-" + time1_out[1];
time1 = time1_out[0] + ":" + time1_out[1];
}
if (time2.contains("-"))
{
time2_out = time1.split(":");
time2_out[1] = "-" + time2_out[1];
time2 = time2_out[0] + ":" + time2_out[1];
}
PeriodFormatterBuilder builder = new PeriodFormatterBuilder();
builder.minimumPrintedDigits(2);
builder.printZeroAlways();
builder.appendHours();
builder.appendLiteral(":");
builder.appendMinutes();
PeriodFormatter pf = builder.toFormatter();
Period period1 = pf.parsePeriod(time1);
Period period2 = pf.parsePeriod(time2);
Period zero = pf.parsePeriod("0:00");
Period normalized;
Period total;
total = period1.plus(period2);
boolean negative = false;
if (total.toStandardDuration().isShorterThan(zero.toStandardDuration()))
{
negative = true;
}
normalized = total.normalizedStandard(PeriodType.time());
return (negative ? "-" : "") + pf.print(normalized);
}
答案 0 :(得分:2)
问题在于解析String。在YodaTime中,负值的表示为-HH:-MM
,因此您的-0:30
表示"减零时,加上30分钟"与00:30相同。
要解决您的问题,您可以执行以下两项操作之一: