The first thing is to extract the hours that you have in the form of String and pass them to a Date type object, if the format you occupy is 2018-08-14 9:31, you do it in the following way:
public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd h:mm", Locale.US);
public static SimpleDateFormat sdfResult = new SimpleDateFormat("HH:mm:ss", Locale.US);
public static SimpleDateFormat sdfResultMinutos = new SimpleDateFormat("m", Locale.US);
public static void main(String[] args) throws ParseException {
Date difference = getDifferenceBetwenDates(sdf.parse("2018-11-01 9:31"), sdf.parse("2018-11-01 9:33"));
System.out.println(sdfResult.format(difference)); //00:02:00
System.out.println(sdfResultMinutos.format(difference) + " Minutos"); //2 Minutos
Date difference2 = getDifferenceBetwenDates(sdf.parse("2018-11-01 9:31"), sdf.parse("2018-11-01 11:28"));
System.out.println(sdfResult.format(difference2)); //01:57:00
System.out.println(sdfResultMinutos.format(difference2) + " Minutos"); //57 Minutos
}
public static Date getDifferenceBetwenDates(Date dateInicio, Date dateFinal) {
long milliseconds = dateFinal.getTime() - dateInicio.getTime();
int seconds = (int) (milliseconds / 1000) % 60;
int minutes = (int) ((milliseconds / (1000 * 60)) % 60);
int hours = (int) ((milliseconds / (1000 * 60 * 60)) % 24);
Calendar c = Calendar.getInstance();
c.set(Calendar.SECOND, seconds);
c.set(Calendar.MINUTE, minutes);
c.set(Calendar.HOUR_OF_DAY, hours);
return c.getTime();
}
What you are doing first is to convert the current value of your date to Date, this is done with the function parse
of SimpleDateFormat
remember that this function requires you to capture a possible exception, once in Date, you can move to milliseconds by means of the function getTime () this will give you a type long
, you would get the difference between these two values and divide them to get seconds, minutes and hours, then create a Calendar object and assign the second minutes and hours calculated previously, when calling the function getTime()
of Calendar
you get an object type Date
, which later you can format your taste by SimpleDateFormat
.
Greetings!