如何计算用户通过android studio中的datepicker输入的两个日期之间的天数

时间:2017-07-11 11:40:22

标签: android android-datepicker date-difference

我正在开发一个我有两个日期选择器的应用程序。如何计算这些日期选择器选择的日期之间的天数?是否有图书馆或内置功能?

以下是我的代码:

public class ApplyLeave extends AppCompatActivity {

    private static final String tag = "ApplyLeave";
    private TextView fomDate;
    private TextView ToDate, days_count;
    private EditText reason;
    private Button save_btn, apply_btn, select_recepeints;
    private TextView leave_type;
    private DatePickerDialog.OnDateSetListener fromdatelistener;
    private DatePickerDialog.OnDateSetListener todatelistener;
    String date1, date2;

    int day1, day2;
    Spinner spinner;
    ArrayAdapter<CharSequence> adapter;
    ListView lv;

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apply_leave);
        reason=(EditText)findViewById(R.id.reason);
        fomDate=(TextView)findViewById(R.id.from_date);
        days_count=(TextView)findViewById(R.id.Days_count);
        ToDate=(TextView)findViewById(R.id.to_date);
        leave_type=(TextView)findViewById(R.id.leave_type);
        save_btn=(Button)findViewById(R.id.save_button);
        apply_btn=(Button)findViewById(R.id.apply_button);
        select_recepeints=(Button)findViewById(R.id.edit_rec);
        lv = (ListView)findViewById(R.id.result);

        final FragmentManager fm=getFragmentManager();
        final  edit_recepients er=new edit_recepients();

        select_recepeints.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                er.show(fm,"TV_tag");

            }
        });
            SharedPreferences sharedPreferences =getSharedPreferences("MyData",MODE_PRIVATE);
             String leave_typ= sharedPreferences.getString("leave_type","null");
        String formdate= sharedPreferences.getString("fromDate","null");
        String toDate= sharedPreferences.getString("ToDate","null");
        String reson= sharedPreferences.getString("reason","null");
    String recepienst= sharedPreferences.getString("recepients","null");
        if(leave_typ.equals("null") || formdate.equals("null") || toDate.equals("null") || reson.equals("null"))
        {
            Toast.makeText(getApplicationContext(), "not data found",Toast.LENGTH_SHORT).show();

        }
        else {

            leave_type.setText(leave_typ);
            fomDate.setText(formdate);
            ToDate.setText(toDate);
            reason.setText(reson);

        }

          save_btn.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  SharedPreferences sharedPreferences=getApplicationContext().getSharedPreferences("MyData",MODE_PRIVATE);
                 SharedPreferences.Editor editor=sharedPreferences.edit();
                  editor.putString("leave_type",leave_type.getText().toString());
                  editor.putString("fromDate",fomDate.getText().toString());
                  editor.putString("ToDate",ToDate.getText().toString());

                  editor.putString("reason",reason.getText().toString());
                  editor.putString("recepients",lv.getAdapter().toString());

                  editor.commit();
                  Toast.makeText(getApplicationContext(),"Application saved",Toast.LENGTH_SHORT).show();

              }
          });

        //spinner for leave
        spinner=(Spinner)findViewById(R.id.leaves);
        adapter=ArrayAdapter.createFromResource(this,R.array.leave_type,R.layout.spinner_layout);
        adapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        //get data from dashboard activity and set into spineer
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if(getIntent().getExtras()!=null) {
                    int select = getIntent().getExtras().getInt("leave");
                    spinner.setSelection(select);
                }

            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

            //listview to display selected persons on Apply leave Acitivity from the onclick event on setttings activiy.
        if(getIntent().getExtras()!=null) {
            Bundle b = getIntent().getExtras();
            String[] resultArr = b.getStringArray("selectedItems");

            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                    R.layout.spinner_layout, resultArr);
            lv.setAdapter(adapter);
        }

        //

        //  Back button in toolbar
        Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setTitleTextColor(getResources().getColor(R.color.o2htextOne));
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        final Drawable upArrow = getResources().getDrawable(R.drawable.back_arrow);
        upArrow.setColorFilter(getResources().getColor(R.color.o2htextOne), PorterDuff.Mode.SRC_ATOP);
        getSupportActionBar().setHomeAsUpIndicator(upArrow);
        if(getSupportActionBar()!=null)
        {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        }//

       fomDate.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onClick(View v) {
                Calendar calendar= Calendar.getInstance();
                int year=calendar.get(Calendar.YEAR);
                int month=calendar.get(Calendar.MONTH);
                int day=calendar.get(Calendar.DAY_OF_MONTH);
                day1=calendar.get(Calendar.DAY_OF_YEAR);

                DatePickerDialog datePickerDialog=new DatePickerDialog(ApplyLeave.this,
                        R.style.DatePickerDialogTheme,
                        fromdatelistener,year,month,day);

                datePickerDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
                datePickerDialog.show();
            }
        });

        fromdatelistener= new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                month=month+1;
                                 Log.d("tag","setDate: "+year+ "/"+month+"/"+dayOfMonth+"");
               date1 =+year+ "/"+month+"/"+dayOfMonth+"";
                fomDate.setText(date1);

            }
        };

        ToDate.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onClick(View v) {
                Calendar calendar= Calendar.getInstance();
                int year=calendar.get(Calendar.YEAR);
                int month=calendar.get(Calendar.MONTH);
                int day=calendar.get(Calendar.DAY_OF_MONTH);
                 day2=calendar.get(Calendar.DAY_OF_YEAR);

                DatePickerDialog datePickerDialog=new DatePickerDialog(ApplyLeave.this,
                      R.style.DatePickerDialogTheme,
                        todatelistener,year,month,day);

                datePickerDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
                datePickerDialog.show();


            }
        });

        todatelistener= new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                month=month+1;
                Log.d("tag","setDate: "+year+ "/"+month+"/"+dayOfMonth+"");

               date2 =+year+ "/"+month+"/"+dayOfMonth+"";
                ToDate.setText(date2);

            }
        };
    }

    @Override
    public void onBackPressed() {
         Intent intent = new Intent(getApplicationContext(), Main3Activity.class);
         intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
         startActivity(intent);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId()==android.R.id.home)
        {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }
}

5 个答案:

答案 0 :(得分:0)

你可以做的只是:

像这样的2个日期 -

Date date1,date2;
//Difference in milliseconds:
long difference = date2.getTime()-date1.getTime();

然后您可以简单地将毫秒转换为小时,秒和日期。

希望这有帮助。

答案 1 :(得分:0)

要获得日期差异,首先需要使用date_from减去date_to 像这样 -

long difference = Math.abs(date_to.getTime() - date_from.getTime());  

然后你可以用下面给出的公式得到天差 -

int days = (int) (difference / (1000 * 60 * 60 * 24)); 

答案 2 :(得分:0)

使用getUnitBetweenDates尝试此操作,您可以计算日期之间没有天数

    SimpleDateFormat dfDate = new SimpleDateFormat("yyyy-MM-dd");
    java.util.Date d = null;
    java.util.Date d1 = null;
    try {
        d = dfDate.parse(2017-08-15);
        d1 = dfDate.parse(2017-08-27);
    } catch (java.text.ParseException e) {
        e.printStackTrace();
    }

    long days = getUnitBetweenDates(d, d1, TimeUnit.DAYS);

    Log.e("Days:-> ", days + "");

答案 3 :(得分:0)

找到解决方案

  1. 如果你的日期是字符串格式

            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            Calendar c= Calendar.getInstance();
            Date c= df.parse("YourStartDate");
            String startDte = df.format(c.getTime());
            Date startTime = df.parse(startDte);
            c.setTime(startTime);
            long startDateinMillis  = c.getTime();
    
            Date c= df.parse("YourEndDate");
            String endDt= df.format(c.getTime());
            Date endTime= df.parse(endDt);
            c.setTime(endTime);
            long endDateInMillis = c.getTime();
    
            long different = endDateInMillis  - startDateinMillis;
            long daysInMilli = hoursInMilli * 24;
    
            long elapsedDays = different / daysInMilli;
            System.out.printf("%d days, elapsedDays);
    
  2. 如果您的日期格式为日期:

           long different = endDate.getTimeInMillis() - startDate.getTimeInMillis();
            long daysInMilli = hoursInMilli * 24;
    
            long elapsedDays = different / daysInMilli;
            System.out.printf("%d days, elapsedDays);
    

答案 4 :(得分:0)

以下是计算两个日期之间差异的方法:

PS:fromDate和toDate是Date类的实例。

long diffInMillies = fromDate.getTime() - toDate.getTime();

int diffInDays = (int) TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);

以下是使用上述代码的示例类:

public class TestClass extends AppCompatActivity {

private DatePickerDialog.OnDateSetListener fromDateListener;
private DatePickerDialog.OnDateSetListener toDateListener;
private TextView fromDateView, toDateView;
private Date fromDate, toDate;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test_class);

    fromDateView = (TextView) findViewById(R.id.fromDateView);
    toDateView = (TextView) findViewById(R.id.toDateView);
    Button button = (Button) findViewById(R.id.button);

    final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd", Locale.US);

    fromDateView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH);
            int day = calendar.get(Calendar.DAY_OF_MONTH);

            DatePickerDialog dialog = new DatePickerDialog(
                    TestClass.this,
                    R.style.DatePickerDialogTheme,
                    fromDateListener, year, month, day);

            dialog.show();
        }
    });

    toDateView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH);
            int day = calendar.get(Calendar.DAY_OF_MONTH);

            DatePickerDialog dialog = new DatePickerDialog(
                    TestClass.this,
                    R.style.DatePickerDialogTheme,
                    toDateListener, year, month, day);

            dialog.show();
        }
    });

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (fromDate == null || toDate == null) return;

            long diffInMillies = fromDate.getTime() - toDate.getTime();

            int diffInDays = (int) TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);

            Log.d("Difference in days", String.valueOf(diffInDays));
        }
    });

    fromDateListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {

            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.YEAR, year);
            calendar.set(Calendar.MONTH, month);
            calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

            fromDate = calendar.getTime();

            fromDateView.setText(dateFormat.format(fromDate));
        }
    };

    toDateListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {

            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.YEAR, year);
            calendar.set(Calendar.MONTH, month);
            calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

            toDate = calendar.getTime();

            toDateView.setText(dateFormat.format(toDate));
        }
    };
}
}