Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get number of days between two calendar instance?

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.

like image 724
Akram Avatar asked Oct 19 '13 05:10

Akram


People also ask

How do you calculate days between two dates?

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.

How do you calculate days between two dates in Kotlin?

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);

What is Calendar getInstance () in Java?

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.


1 Answers

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)); } 
like image 160
Jk1 Avatar answered Oct 01 '22 14:10

Jk1