How to subtract dates in Java?
StartDate: 2016-05-11 00:46;
EndDate: 2016-05-12 12:26;
the result should be: 1d 11h 40min
2
3 answers
Or maybe a monster)):
public static void main(String[] args) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date dateS = format.parse("2016-05-11 00:46");
Date dateE = format.parse("2016-05-12 12:26");
long delt = dateE.getTime() - dateS.getTime();
String result = String.format("%dд %dч %dмин",
delt / 86400000,
(delt % 86400000) / 3600000,
(delt % 3600000) / 60000);
System.out.println(result);
}
Answer: 1d 11h 40min
86400000-respectively days.
Next, we operate with the remainder of the division))
1
Author: Артём -... . .-.. .-.- . .--, 2017-06-21 11:20:27
You can use the java.time.*
package that appeared in Java 8:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime start = LocalDateTime.parse("2016-05-11 00:46", formatter);
LocalDateTime end = LocalDateTime.parse("2018-05-12 12:26", formatter);
Duration duration = Duration.between(start, end);
System.out.printf(
"%dд %dч %dмин%n",
duration.toDays(),
duration.toHours() % 24,
duration.toMinutes() % 60
);
1
Author: Alex Chermenin, 2017-11-29 08:09:42
You need to convert your dates to the Date type and assign them to two variables, startDate
and endDate
Date startDate = ...
Date endDate = ...
long duration = endDate.getTime() - startDate.getTime();
long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(duration);
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);
long diffInHours = TimeUnit.MILLISECONDS.toHours(duration);
0
Author: DevOma, 2017-06-24 20:21:45