I have two date like:
String date_1="yyyyMMddHHmmss"; String date_2="yyyyMMddHHmmss";
I want to print the difference like:
2d 3h 45m
How can I do that? Thanks!
This example demonstrates how do I get the difference between two dates in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
Use the DATEDIF function when you want to calculate the difference between two dates. First put a start date in a cell, and an end date in another. Then type a formula like one of the following.
DateTimeUtils obj = new DateTimeUtils(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/M/yyyy hh:mm:ss"); try { Date date1 = simpleDateFormat.parse("10/10/2013 11:30:10"); Date date2 = simpleDateFormat.parse("13/10/2013 20:35:55"); obj.printDifference(date1, date2); } catch (ParseException e) { e.printStackTrace(); } //1 minute = 60 seconds //1 hour = 60 x 60 = 3600 //1 day = 3600 x 24 = 86400 public void printDifference(Date startDate, Date endDate) { //milliseconds long different = endDate.getTime() - startDate.getTime(); System.out.println("startDate : " + startDate); System.out.println("endDate : "+ endDate); System.out.println("different : " + different); long secondsInMilli = 1000; long minutesInMilli = secondsInMilli * 60; long hoursInMilli = minutesInMilli * 60; long daysInMilli = hoursInMilli * 24; long elapsedDays = different / daysInMilli; different = different % daysInMilli; long elapsedHours = different / hoursInMilli; different = different % hoursInMilli; long elapsedMinutes = different / minutesInMilli; different = different % minutesInMilli; long elapsedSeconds = different / secondsInMilli; System.out.printf( "%d days, %d hours, %d minutes, %d seconds%n", elapsedDays, elapsedHours, elapsedMinutes, elapsedSeconds); }
out put is :
startDate : Thu Oct 10 11:30:10 SGT 2013 endDate : Sun Oct 13 20:35:55 SGT 2013 different : 291945000 3 days, 9 hours, 5 minutes, 45 seconds
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With