我正在开发Android应用程序,我需要计算一些时间(使用Joda libs)。 我想知道是否存在这样做的Java类。
我想计算的案例(例如):
案例1:
t1 = "13:40"
t2 = "12:30"
result = t1 + t2 --> 26:10
案例2:
t1 = "13:40"
t2 = "12:30"
result = t1 - t2 --> 1:10
案例2.1:
t1 = "13:40"
t2 = "14:00"
result = t1 - t2 --> -0:20
谢谢! :)
答案 0 :(得分:2)
以下JodaTime-code处理输入和结果作为时间量,而不是时间点:
案例1:
PeriodFormatterBuilder builder = new PeriodFormatterBuilder();
builder.minimumPrintedDigits(2);
builder.printZeroAlways();
builder.appendHours();
builder.appendLiteral(":");
builder.appendMinutes();
PeriodFormatter pf = builder.toFormatter();
Period period1 = pf.parsePeriod("13:40");
Period period2 = pf.parsePeriod("12:30");
Period total = period1.plus(period2);
Period normalized = total.normalizedStandard(PeriodType.time());
System.out.println("TOTAL PERIOD: " + total); // PT25H70M
System.out.println("NORMALIZED PERIOD: " + normalized); // PT26H10M
System.out.println("FORMATTED NORMALIZED PERIOD: " + pf.print(normalized)); // 26:10
案例2 + 2.1:
PeriodFormatterBuilder builder = new PeriodFormatterBuilder();
builder.minimumPrintedDigits(2);
builder.printZeroAlways();
builder.appendHours();
builder.appendLiteral(":");
builder.appendMinutes();
PeriodFormatter pf = builder.toFormatter();
Period period1 = pf.parsePeriod("13:40");
Period period2 = pf.parsePeriod("14:00");
boolean negative = false;
if (period1.toStandardDuration().isShorterThan(period2.toStandardDuration())) {
Period tmp = period1;
period1 = period2;
period2 = tmp;
negative = true;
}
Period total = period1.minus(period2);
Period normalized = total.normalizedStandard(PeriodType.time());
System.out.println("NORMALIZED PERIOD: " + (negative ? "-" : "") + normalized);
System.out.println(
"FORMATTED NORMALIZED PERIOD: " + (negative ? "-" : "") + pf.print(normalized)
); // -00:20
请注意,由于JodaTime的标志处理不充分(喜欢打印不在前面的标志,而是在句点表达式中打印宽度),因此需要一些笨重的解决方法。
答案 1 :(得分:1)
我在这里计算05:00:00 PM这种格式你可以采取任何你想要的格式:
String string1 = "05:00:00 PM";
Date time1 = new SimpleDateFormat("HH:mm:ss aa").parse(string1);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);
String string2 = "09:00:00 AM";
Date time2 = new SimpleDateFormat("HH:mm:ss aa").parse(string2);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time2);
calendar2.add(Calendar.DATE, 1);
Date x = calendar1.getTime();
Date xy = calendar2.getTime();
long diff = x.getTime() - xy.getTime();
diffMinutes = diff / (60 * 1000);
float diffHours = diffMinutes / 60;
System.out.println("diff hours" + diffHours);