0

I am trying to convert a date from date picker to get number of days in Android. For example if I choose 19/11/2015, the number of days should be 2 days. I need to find a solution for this as it is important for my project. There are many solutions on the web for getting the number of days between two dates but not from a single date. Can anyone help please?

Below is the method where I have to set and convert the date.

public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
    String date = +dayOfMonth+"/"+(++monthOfYear)+"/"+year;

    Calendar end = Calendar.getInstance();
    end.set(year, monthOfYear, dayOfMonth);
    long timenow= System.currentTimeMillis();


    long endDate = end.getTimeInMillis();

    long diffTime = endDate - timenow;
   days = (int) (diffTime / (1000 * 60 * 60 * 24));
    DateFormat dateFormat = DateFormat.getDateInstance();
    dateFormat.format(endDate);
    //System.out.println(diffDays);


    dateTextView.setText(Integer.toString(days));
spykeburn
  • 153
  • 1
  • 19

1 Answers1

1

Answer for:

Right now it is giving me this bug

The reason for the error is you are trying to set an int as value to dateTextView.

Instead of dateTextView.setText(days); try dateTextView.setText(Integer.toString(days));

Swagata Acharyya
  • 647
  • 4
  • 10
  • The bug is gone but I am not getting the correct number of days. It shows 16787. May be this is not the way to get the number of days from the current date? – spykeburn Nov 16 '15 at 20:23
  • Then you can use any standard example of finding difference between two dates. One Date will be current Date, another date will be the date as constructed from the user input. There are a lot of examples available that finds difference between two dates. One such example: http://stackoverflow.com/questions/1555262/calculating-the-difference-between-two-java-date-instances – Swagata Acharyya Nov 16 '15 at 20:47
  • I have updated my code. I am getting 32 days instead of 2 days. like 34 days instead of 4. Got me? I don't know what's wrong. Can you please correct me? – spykeburn Nov 17 '15 at 05:15
  • OK I got it. Actually the month numbers were zero based. January -0 and Dec- 11. Thanks a lot. – spykeburn Nov 17 '15 at 05:47