android - Sum and difference beetwen hours in Java (over 24h) -
i'm developing android app , need calculate times (with joda libs). know if exist java class this.
the cases calculate (in example):
case 1:
t1 = "13:40" t2 = "12:30" result = t1 + t2 --> 26:10
case 2:
t1 = "13:40" t2 = "12:30" result = t1 - t2 --> 1:10
case 2.1:
t1 = "13:40" t2 = "14:00" result = t1 - t2 --> -0:20
thanks!! :)
following jodatime-code handles both inputs , result temporal amounts, not points in time:
case 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
case 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
note due insufficient sign handling of jodatime (which likes print sign not in front midth inside period expression) clunky workaround necessary.
Comments
Post a Comment