mystery on timstamp getTime diff

here is my code:

System.out.println(" serverStartTime:" + serverStartTime + " serverRunningTime:" + serverRunningTime);

Timestamp sTime = convertTimeFormat(serverStartTime, "MMM d, yyyy H:mm:ss a z");
Timestamp eTime = convertTimeFormat(serverRunningTime, "MMM d, yyyy H:mm:ss a z");
long diff = (eTime.getTime() - sTime.getTime());
System.out.println("eTime.getTime():" + eTime.getTime() + " sTime.getTime():" + sTime.getTime() + " Time diff:" + diff);

The convertTime looks like:

private Timestamp convertTimeFormat(String msgDate, String srcDateFormat) {
    SimpleDateFormat sdf = new SimpleDateFormat(srcDateFormat);
    SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
        Date d = sdf.parse(msgDate);
        String formattedTime = output.format(d);
        return Timestamp.valueOf(formattedTime);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return null;
}

The output is:

serverStartTime:Sep 22, 2016 12:42:56 AM PDT serverRunningTime:Sep 22, 2016 1:33:42 AM PDT
eTime.getTime():1474533222000 sTime.getTime():1474573376000 Time diff:-40154000

notice that running time value is smaller then start time. why?

Jon Skeet
people
quotationmark

You used H in your time format - that's a 24-hour time, so your "start" time is just after midday, more than 10 hours later than your end time. Yes, you've got the "AM" in the format string as well, but I believe that's being ignored due to your use of H. Use h instead. Always, always check format strings very carefully.

Timestamp sTime = convertTimeFormat(serverStartTime, "MMM d, yyyy h:mm:ss a z");
Timestamp eTime = convertTimeFormat(serverRunningTime, "MMM d, yyyy h:mm:ss a z");

Note that another way of working out this problem would have been to print the intermediate values in your yyyy-MM-dd HH:mm:ss format. I suspect you'd have seen something like:

2016-09-22 12:42:56
2016-09-22 01:33:42

It's not clear whether that's actually what you'd have , as you haven't set the time zone in your output format, which is almost certainly a problem in itself. I would avoid the extra string round-trip if possible.

people

See more on this question at Stackoverflow