I am having an issue while parsing day and time to get the total hours and minutes in java.
If I calculate total hours starting from 'Mon 22:00' to 'Tue 22:00' then I am getting correct total hours 24. But If I calculate total hours starting from 'Wed 22:00' to current day and time like 'Thu 12:45' then I am getting 'Hours : -153 Min : -15'.
This is the case only for Wednesday and Thursday. For rest of the days it is working fine.
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class Test {
private static DateFormat dateFormat = new SimpleDateFormat("EEE HH:mm");
private static DateFormat dayFormat = new SimpleDateFormat("E");
private static Calendar calendar = Calendar.getInstance();
public static void main(String[] args) {
try {
Date date1 = dateFormat.parse("Wed 22:00");
Date date2 = dateFormat.parse(dayFormat.format(calendar.getTime()) + " " + calendar.getTime().getHours() + ":"
+ calendar.getTime().getMinutes());
long hours2 = getDurationInHours(date1, date2);
long min = getDurationInMin(date1, date2);
System.out.println("Hours : " + hours2 + " Min : " + min);
} catch (Exception e) {
e.printStackTrace();
}
}
public static long getDurationInHours(Date returnTime, Date leaveTime) {
long durationInMillis = leaveTime.getTime() - returnTime.getTime();
long hours = TimeUnit.MILLISECONDS.toHours(durationInMillis);
return hours;
}
public static long getDurationInMin(Date returnTime, Date leaveTime) {
long durationInMillis = leaveTime.getTime() - returnTime.getTime();
long min = TimeUnit.MILLISECONDS.toMinutes(durationInMillis) % 60;
return min;
}
}