문제

java.text.DateFormat df = new java.text.SimpleDateFormat("hhmm");
java.util.Date date1 = df.parse(parts[12]);
java.util.Date date2 = df.parse(parts[13]);
        long diff = (date2.getTime() - date1.getTime());
        int timeinminutes = (int) (diff/(1000*60));

I have a series of times that I am getting off a website that is in a column. The times are formatted as followed: 1040, 1149 which work with my code. However some times are formatted as 945 or 656 (military time) which messes up my code how should I format it thanks!

도움이 되었습니까?

해결책

An easy way would just be to add a leading 0 to the parts string. For example:

if(parts[12].length == 3)
    parts[12] = "0"+parts[12];

If you're trying to read military time as opposed to the 12 hour system, you need to modify your pattern to "HHmm". "HH" means 24 hour, "hh" means 12 hour. You'll find a full list in the Oracle documentation.

다른 팁

I would do it like this (create 2 new variables to hold the times for both dates). Also since you're using military time, you need to use capital HH, which tells your date format to use 24 hour clock.

java.text.DateFormat df = new java.text.SimpleDateFormat("HHmm");

// Create 2 new variables to hold the date parts (times)
String dp1 = (parts[12].length == 3) ? "0" + parts[12] : parts[12]; 
String dp2 = (parts[13].length == 3) ? "0" + parts[13] : parts[13];

java.util.Date date1 = df.parse(dp1);
java.util.Date date2 = df.parse(dp2);
long diff = (date2.getTime() - date1.getTime());
int timeinminutes = (int) (diff/(1000*60));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top