-1

I keep getting the wrong amount on my calculation of getting the amount of total days.

I want to get the absolute number of days from and to a certain date on my calendar. E.G - 1st Dec to 6th Dec should be 6 days, 15th September to 17th December should be 3 days. But it's not giving me the results I want nor do I think I am doing this the best way :(

Code:

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;

import com.borax12.materialdaterangepicker.date.DatePickerDialog;

import java.util.Calendar;

/**
 * Created by hp1 on 21-01-2015.
 */
public class Tab2 extends Fragment implements DatePickerDialog.OnDateSetListener{

    DatePicker pickerDate;
    TextView dateTextView;
    private boolean mAutoHighlight;
    Calendar to;
    Calendar from;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final View v = inflater.inflate(R.layout.tab2,container,false);

        Button dateButton = (Button)v.findViewById(R.id.button2);
        dateTextView = (TextView)v.findViewById(R.id.textView5);

        CheckBox ahl = (CheckBox) v.findViewById(R.id.autohighlight_checkbox);
        ahl.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                mAutoHighlight = b;
            }
        });

        // Show a datepicker when the dateButton is clicked
        dateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                to = Calendar.getInstance();
                DatePickerDialog dpd = com.borax12.materialdaterangepicker.date.DatePickerDialog.newInstance(
                        Tab2.this,
                        to.get(Calendar.YEAR),
                        to.get(Calendar.MONTH),
                        to.get(Calendar.DAY_OF_MONTH)
                );
                dpd.setAutoHighlight(mAutoHighlight);
                dpd.show(getActivity().getFragmentManager(), "Datepickerdialog");

                dpd.setYearRange(2016, 2017);
            }

        });

        int year,monthofyear,dayofmonth;
        return v;
    }

    @Override
    public void onResume() {
        super.onResume();
        DatePickerDialog dpd = (DatePickerDialog) getActivity().getFragmentManager().findFragmentByTag("Datepickerdialog");
        if(dpd != null) dpd.setOnDateSetListener(this);
    }

    @Override
    public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth,int yearEnd, int monthOfYearEnd, int dayOfMonthEnd) {

        to.set(Calendar.YEAR, year);
        to.set(Calendar.MONTH, monthOfYear);
        to.set(Calendar.DAY_OF_MONTH, dayOfMonth);

        from = Calendar.getInstance();

        from.set(Calendar.YEAR, yearEnd);
        from.set(Calendar.MONTH, monthOfYearEnd);
        from.set(Calendar.DAY_OF_MONTH, dayOfMonthEnd);

        long diff = to.get(Calendar.DAY_OF_MONTH) - from.get(Calendar.DAY_OF_MONTH);
        Log.e("Amount of Days is ", "" +   diff);

        Log.e(dayOfMonth + "TOOOOOOOOO" + dayOfMonthEnd, "DDDDDDDDDDDDDDDDDDDDDDDDDDDDD" + Math.abs(diff));

        String date = "You picked the following date: From- "+dayOfMonth+"/"+(++monthOfYear)+"/"+year+" To "+dayOfMonthEnd+"/"+(++monthOfYearEnd)+"/"+yearEnd;
        dateTextView.append(new StringBuilder().append(date) + "\n");
    }

}

I'm trying to do this within the onDateSet method.

Thanks

Edit:

I've tried this:

long diff = to.get(Calendar.DAY_OF_MONTH) - from.get(Calendar.DAY_OF_MONTH);
diff = diff + 1;

The results I am getting are strange as I get:

1st to 4th - Gives me 2 days - should give me 4

13th to 20th Gives me 6 days - should give me 8 days

Edit:

I need another way of doing this as it was giving me minus values I swapped the to and the from minus. But I have an issue when I do 29th to 3rd for instance. Is there another way I can do this?

Sam
  • 1,207
  • 4
  • 26
  • 50
  • 1
    In a strict definition of "days between", which assumes that you mean starting and ending at the same time of day, i.e. noon to noon or 00:00 to 00:00, Dec 1 to Dec 6 is ***five*** days. Starting at 00:00 December 1 to 00:00 December 2 is exactly 24 hours, or one day. If you really want the interval to start at 00:00 of the first day and end at 24:00 of the last day you need to add 1 to the "days between" result. Also, that's way too much code, it is trivial in Java as I indicated in my answer to the duplicate question. – Jim Garrison Sep 01 '17 at 21:13
  • Yes so if we were counting noon to noon using the strict definition this would be more for number of nights, such as booking a room for stay which would mean Dec 1 to Dec 6 is five. But if we were counting sick days for instance then this would be total 6 days right? In the code I tried to add diff += 1 but this didn;t work. – Sam Sep 01 '17 at 21:20
  • The link you gave for a duplicate answer as well is ChronoUnit which is only used for higher api levels, I'm trying to import it but it cannot be resolved on Android Studio. – Sam Sep 01 '17 at 21:28
  • If you're using Java 8 it should be available. What version of Java are you on? – Jim Garrison Sep 01 '17 at 21:31
  • Date intervals are tricky as there are multiple ways to interpret them. All APIs use the mathematical definition, so if you want a different interpretation you'll need to explain what didn't work about adding 1 to the interval. What result did you _actually_ get and why is it not acceptable? – Jim Garrison Sep 01 '17 at 21:32
  • If you can [edit] your question to restate it, explaining what doesn't work about just adding 1, so it's not a duplicate of the other question, I'll rescind the duplicate closure. – Jim Garrison Sep 01 '17 at 21:34
  • okay will edit thanks – Sam Sep 01 '17 at 21:35
  • Java version installed on my machine is 1.8 – Sam Sep 01 '17 at 21:46
  • Okay bigger problem the way I am doing it wont work, it was using minus values then incrementing gave me different values :( – Sam Sep 01 '17 at 22:21

1 Answers1

0

Solved this by using the Joda time:

Added the dependency to build.gradle:

compile 'net.danlew:android.joda:2.9.9'

Increment the days below to give me the exact days:

            to.set(Calendar.YEAR, year);
            to.set(Calendar.MONTH, monthOfYear);
            to.set(Calendar.DAY_OF_MONTH, dayOfMonth);

            from = Calendar.getInstance();
            from.set(Calendar.YEAR, yearEnd);
            from.set(Calendar.MONTH, monthOfYearEnd);
            from.set(Calendar.DAY_OF_MONTH, dayOfMonthEnd);

            Date toTime = to.getTime();
            Date fromTime = from.getTime();

            int days2 = Days.daysBetween(new DateTime(toTime), new DateTime(fromTime)).getDays();
            days2++;
Sam
  • 1,207
  • 4
  • 26
  • 50