1

Friends, I am looking to calculate the difference in days.

Hey suppose if I enter 31st Aug 23:59:00 and next date 1 Sept 00:02:00 , I need to show the record as 1 day.

Please help me for this one.

Right now I am calculating the same using .getTimeInMillis() but it is not giving me expected results for the date condition mentioned above.

Ram kiran Pachigolla
  • 20,897
  • 15
  • 57
  • 78
onkar
  • 19
  • 1
  • 6
  • Do you need day and time difference? – arshad kr Sep 25 '12 at 11:16
  • Find the ans - http://stackoverflow.com/questions/3299972/difference-in-days-between-two-dates-in-java – Subhrajyoti Majumder Sep 25 '12 at 11:17
  • possible duplicate of [Calculating the Difference Between Two Java Date Instances](http://stackoverflow.com/questions/1555262/calculating-the-difference-between-two-java-date-instances) – DNA Sep 25 '12 at 11:19
  • @DNA how do I add joda methods ? – onkar Sep 25 '12 at 11:27
  • Same as for any Java library - download from the Jodatime website, and add the jar file to your classpath (how you do this depends on your development environment). Import the Joda classes as shown in some of the examples below... – DNA Sep 25 '12 at 11:32

7 Answers7

1

I you look for day and time difference then, use my code

public class AndroidWebImage extends Activity {

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) 
{
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  Date sdate=Calendar.getInstance().getTime();
  SimpleDateFormat format = new SimpleDateFormat("dd/MM/yy HH:mm:ss");

  String setDate = "13/09/12 10:20:43";
  Date AlarmDate=new Date(setDate);
  String currentDate = format.format(sdate);

  Date d1 = null;
  Date d2 = null;
  try {
      d1 = format.parse(setDate);
      d2 = format.parse(currentDate);
  } catch (ParseException e) {
      e.printStackTrace();
  }    
 //Comparison
  long diff = d1.getTime() - d2.getTime();
  long diffSeconds = diff / 1000 % 60;  

  long days = (int) (diff / (1000 * 60 * 60 * 24));
  long diffHours = (int) ((diff- (1000 * 60 * 60 * 24 * days)) / (1000 * 60 * 60));
  long diffMinutes = (int) (diff- (1000 * 60 * 60 * 24 * days) - (1000 * 60 * 60 *      diffHours))/ (1000 * 60);

  int curhour=sdate.getHours();
  int curmin=sdate.getMinutes();
  int alarmhour=AlarmDate.getHours();
  int alarmmin=AlarmDate.getMinutes();
  if(curhour==alarmhour && curmin==alarmmin)
  {
      Toast.makeText(getApplicationContext(), String.valueOf(days+"days\n"+diffHours+"hrs"+diffMinutes+"min\n"+diffSeconds+"sec"),Toast.LENGTH_LONG).show();
  }
  else if(curhour>=alarmhour && curmin>=alarmmin || curhour<=alarmhour && curmin<=alarmmin)
  {
      Toast.makeText(getApplicationContext(), String.valueOf(days+"days\n"+diffHours+"hrs"+diffMinutes+"min\n"+diffSeconds+"sec"),Toast.LENGTH_LONG).show();
  }




 }
}
arshad kr
  • 357
  • 3
  • 16
  • Hey mate I dont think this will give me expected output. – onkar Sep 25 '12 at 11:25
  • try and works.. few days before I did. And date formats may variate – arshad kr Sep 25 '12 at 11:27
  • I enter 31st Aug 23:59:00 and next date 1 Sept 00:02:00 , I need to show the record as 1 day. – onkar Sep 25 '12 at 11:32
  • record as 1 day.. could you elaborate so that I can give you snippet. – arshad kr Sep 25 '12 at 11:35
  • Hey mate I am getting date& time from user and need to calculate the difference and show it. (Just a condition I am thinking) – onkar Sep 25 '12 at 11:47
  • Fine.. then above code will work.. pass the date and time to setDate. Am sure you are looking for above code.. you can't make day difference in single query as do in .net so did code above. – arshad kr Sep 25 '12 at 11:53
  • String setDate = "13/09/12 23:59:43"; Date AlarmDate=new Date(setDate); // String currentDate = format.format(sdate); String currentDate="14/09/12 00:01:43"; Its giving 00 days 00 hours 02 mins 00 secs – onkar Sep 25 '12 at 12:10
  • yeah! set date to be greater than current day.. above snippet code as like... change according to your code.. – arshad kr Sep 25 '12 at 13:06
0

You need to get rid of the timestamps and then subtract dates to get the difference in dates or you can use Joda-time as below:

import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.Days;

Date past = new Date(112, 8, 1); 
Date today = new Date(112, 7, 30); 
int days = Days.daysBetween(new DateTime(past), new DateTime(today)).getDays(); 
Bharat Sinha
  • 13,973
  • 6
  • 39
  • 63
0

You can't do this with millis, because you need to know where the day boundary falls (i.e. midnight). A millisecond either side of midnight means two different days.

You need to use a Calendar to determine how many days lie within the interval between your two dates. The JodaTime library has a lot of additional support for this kind of calculation.

See also Calculating the difference between two Java date instances

Community
  • 1
  • 1
DNA
  • 42,007
  • 12
  • 107
  • 146
0

Your're just trying to find the number of days, right?

Try looking at this, it might have what you are looking for.

Community
  • 1
  • 1
AJMansfield
  • 4,039
  • 3
  • 29
  • 50
0

i made this code before, its may helps you

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 * @author MErsan
 */
public class DateFormatter {

    public static String formatDate(long time) {
        StringBuilder result = new StringBuilder();

        // 1- Check the year
        // 2- Check the Month
        // 3- Check the Day
        // 4- Check the Hours

        Date myDate = new Date(time);
        Date todayDate = new Date(System.currentTimeMillis());

        if (todayDate.getYear() - myDate.getYear() != 0) {
            // Not same year, and should append the whole time
            return DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(myDate);
        }
        // Same Year
        // now Check the month
        if (todayDate.getMonth() - myDate.getMonth() != 0) {
            return new SimpleDateFormat("MMM dd, hh:mm a").format(myDate);// Aug
            // 16,
            // 11:55
            // PM
        }

        // Now Same Month
        // Check the day
        int daysDiff = todayDate.getDate() - myDate.getDate();
        if (daysDiff == 1) {// Yesterday
            result.append("Yesterday").append(' ');
            result.append(new SimpleDateFormat("hh:mm a").format(myDate));
            return result.toString();
        } else if (daysDiff != 0) {
            return new SimpleDateFormat("MMM dd, hh:mm a").format(myDate);// Aug
            // 16,
            // 11:55
            // PM
        }

        // Same Day :')
        // Check the hour
        int hoursDiff = todayDate.getHours() - myDate.getHours();
        if (hoursDiff < 0) {// Invalid Time
            // :@
            result.append("Today").append(' ');
            result.append(new SimpleDateFormat("hh:mm a").format(myDate));
            return result.toString();
        } else if (hoursDiff > 3) {// Not Same Hour, Hour Diff more than 3 hours
            result.append("Today").append(' ');
            result.append(new SimpleDateFormat("hh:mm a").format(myDate));
            return result.toString();
        } else if (hoursDiff != 0) {// Hours Diff less than 3 hours, but not
            // current hour
            int mintuesDiff = todayDate.getMinutes() - myDate.getMinutes();

            result.append("Before").append(' ');
            result.append(hoursDiff).append(' ');
            result.append("Hours").append(' ');
            result.append("and").append(' ');
            result.append(Math.abs(mintuesDiff)).append(' ');
            result.append("Minutes");
            System.err.println("Case 6");
            return result.toString();
        } else if (hoursDiff == 0) {// Same Hours
            int mintuesDiff = todayDate.getMinutes() - myDate.getMinutes();
            if (mintuesDiff < 1) {// Seconds Only {Same Minute}
                int secondsDiff = todayDate.getSeconds() - myDate.getSeconds();
                result.append("Before").append(' ');
                result.append(Math.abs(secondsDiff)).append(' ');
                result.append("Seconds");
                return result.toString();
            } else {
                result.append("Before").append(' ');
                result.append(Math.abs(mintuesDiff)).append(' ');
                result.append("Minutes");
                return result.toString();
            }
        }

        // Default
        return DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(myDate);
    }
}
Mohammad Ersan
  • 12,304
  • 8
  • 54
  • 77
0
import java.util.Calendar;

public class DateDifference
{  
    public static void main(String[] args)
    {
        Calendar calendar1 = Calendar.getInstance();
        Calendar calendar2 = Calendar.getInstance();

        calendar1.set(2012, 01, 10);
        calendar2.set(2012, 07, 01);

        long milliseconds1 = calendar1.getTimeInMillis();
        long milliseconds2 = calendar2.getTimeInMillis();

        long diffDays = diff / (24 * 60 * 60 * 1000);

        System.out.println("Time in days: " + diffDays + " days.");
    }
} 
Azodious
  • 13,752
  • 1
  • 36
  • 71
0

Re-post:

There's a simple solution, that at least for me, is the only feasible solution.

The problem is that all the answers I see being tossed around - using Joda, or Calendar, or Date, or whatever - only take the amount of milliseconds into consideration. They end up counting the number of 24-hour cycles between two dates, rather than the actual number of days. So something from Jan 1st 11pm to Jan 2nd 1am will return 0 days.

To count the actual number of days between startDate and endDate, simply do:

// Find the sequential day from a date, essentially resetting time to start of the day
long startDay = startDate.getTime() / 1000 / 60 / 60 / 24;
long endDay = endDate.getTime() / 1000 / 60 / 60 / 24;

// Find the difference, duh
long daysBetween = endDay - startDay;

This will return "1" between Jan 2nd and Jan 1st. If you need to count the end day, just add 1 to daysBetween (I needed to do that in my code since I wanted to count the total number of days in the range).

Community
  • 1
  • 1
zeh
  • 10,130
  • 3
  • 38
  • 56