Sprawa jest nastepujaca: mam dwie godziny (np 20:45 i 8:00) i chce policzyc jaka jest miedzy nimi roznica , czyli ile godzin trzeba dodac do pierwszej zeby wyszla druga. Czy znacie moze jakis gotowy sprytny algorytm ?? :>
0
0
ponizszy kod zawsze traktuje pierwsza godzine jako wczesniejsza, druga jako pozniejsza
package test;
import java.text.DateFormat;
import java.util.Date;
public class Test {
public static long DAY_MILLIS = 24 * 3600 * 1000;
public static void main(String[] args) throws Exception {
DateFormat df = DateFormat.getTimeInstance(DateFormat.SHORT);
Date d1 = df.parse("20:00");
Date d2 = df.parse("01:30");
long difference = d2.getTime() - d1.getTime();
// if negative, means we have want to flip to another day
if (difference < 0) {
difference += DAY_MILLIS;
}
System.out.println(difference / 1000 / (double) 3600 + " h");
}
}
0
package test;
import java.text.DateFormat;
import java.util.Date;
public class Test {
public final static int MINUTE_MILLIS = 60 * 1000;
public final static int HOUR_MILLIS = MINUTE_MILLIS * 60;
public final static int DAY_MILLIS = HOUR_MILLIS * 24;
public static void main(String[] args) throws Exception {
DateFormat df = DateFormat.getTimeInstance(DateFormat.SHORT);
Date d1 = df.parse("20:11");
Date d2 = df.parse("01:30");
long difference = d2.getTime() - d1.getTime();
// if negative, means we have want to flip to another day
if (difference < 0) {
difference += DAY_MILLIS;
}
int h = (int) difference / HOUR_MILLIS;
int m = (int) (difference - (h * HOUR_MILLIS)) / MINUTE_MILLIS;
System.out.println(h + ":" + m);
}
}