Java: die Berechnung der Dauer

Habe ich den folgenden code, um die Berechnung der Dauer zwischen zwei timestamps, die sich in zwei verschiedenen Formaten:

public class dummyTime {
public static void main(String[] args) {
    try {
        convertDuration("2008-01-01 01:00 pm - 01:56 pm");
        convertDuration("2008-01-01 8:30 pm - 2008-01-02 09:30 am");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private static String convertDuration(String time) throws Exception {
    String ts[] = time.split(" - ");
    SimpleDateFormat formatNew = new SimpleDateFormat("HH:mm");
    Date beg, end;
    String duration = null;

    beg = getDateTime(ts[0]);
    end = getDateTime(ts[1], beg);

    duration = formatNew.format(end.getTime() - beg.getTime());
    System.out.println(duration + " ///" + time + " ///" + beg + " ///"
            + end);

    return duration;
}

private static Date getDateTime(String dateTime) throws ParseException {
    DateFormat formatOldDateTime = new SimpleDateFormat(
            "yyyy-MM-dd hh:mm aa");
    DateFormat formatOldTimeOnly = new SimpleDateFormat("hh:mm aa");
    Date date = null;

    try {
        date = formatOldDateTime.parse(dateTime);
    } catch (ParseException e) {
        date = formatOldTimeOnly.parse(dateTime);
    }

    return date;
}

private static Date getDateTime(String dateTime, Date orig)
        throws ParseException {
    Date end = getDateTime(dateTime);

    if (end.getYear() == 70) {
        end.setYear(orig.getYear());
        end.setMonth(orig.getMonth());
        end.setDate(orig.getDate());
    }

    return end;
}
}

Die Ausgabe, die es erzeugt, ist:

01:56 ///2008-01-01 01:00 pm - 01:56 pm ///Tue Jan 01 13:00:00 CET 2008 ///Tue Jan 01 13:56:00 CET 2008
14:00 ///2008-01-01 8:30 pm - 2008-01-02 09:30 am ///Tue Jan 01 20:30:00 CET 2008 ///Wed Jan 02 09:30:00 CET 2008

Meine Fragen sind:

  1. Warum sind die Ergebnisse immer falsch
    (immer +1h)?
  2. Was ist besser
    Weg zu identifizieren, ohne Zeitstempel
    Tag? == 70 sieht nicht gut aus und die
    getDay & setDay Funktionen sind
    veraltet auch.

Vielen vielen Dank, dieses Problem hat mich verrückt wurde für mehrere Stunden.

Die Eingänge sind inkonsistent. Die meisten der Zeit-von-Tag-Werte haben eine Polsterung null, aber 8:30 pm lässt.

InformationsquelleAutor MrG | 2009-01-25

Schreibe einen Kommentar