I want to find the difference between two Calendar
objects in number of days if there is date change like If clock ticked from 23:59-0:00 there should be a day difference.
i wrote this
public static int daysBetween(Calendar startDate, Calendar endDate) { return Math.abs(startDate.get(Calendar.DAY_OF_MONTH)-endDate.get(Calendar.DAY_OF_MONTH)); }
but its not working as it only gives difference between days if there is month difference its worthless.
To calculate the number of days between two dates, you need to subtract the start date from the end date. If this crosses several years, you should calculate the number of full years. For the period left over, work out the number of months. For the leftover period, work out the number of days.
startDateValue = new Date(startDate); endDateValue = new Date(endDate); long diff = endDateValue. getTime() - startDateValue. getTime(); long seconds = diff / 1000; long minutes = seconds / 60; long hours = minutes / 60; long days = (hours / 24) + 1; Log. d("days", "" + days);
The getInstance() method in Calendar class is used to get a calendar using the current time zone and locale of the system. Syntax: public static Calendar getInstance() Parameters: The method does not take any parameters. Return Value: The method returns the calendar.
Try the following approach:
public static long daysBetween(Calendar startDate, Calendar endDate) { long end = endDate.getTimeInMillis(); long start = startDate.getTimeInMillis(); return TimeUnit.MILLISECONDS.toDays(Math.abs(end - start)); }
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