0

I want to count the elapsed days and show them in a textview. I'm using a datepickerdialog for select the date, from this date that shows how many days have passed.

when I press the textview the datepickerdialog opens,

This is the code:

public class MainActivity extends AppCompatActivity {
    TextView cal, dias;

    private String Parto;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        cal = (TextView) findViewById(R.id.calen);
        dias = (TextView) findViewById(R.id.days);

        cal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            final Calendar calendar = Calendar.getInstance();
                DatePickerDialog datePickerDialog = new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        Calendar calendar1 = Calendar.getInstance();
                        calendar1.set(Calendar.YEAR,year);
                        calendar1.set(Calendar.MONTH,month);
                        calendar1.set(Calendar.DAY_OF_MONTH,dayOfMonth);
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
                        Date date = calendar1.getTime();
                        Parto = simpleDateFormat.format(date);
                        cal.setText(Parto);
                    }
                },calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                datePickerDialog.show();
            }
        });



    }

} 

I want to show the elapsed days in textview days

Thanks very much

Rahman Haroon
  • 1,088
  • 2
  • 12
  • 36
Armayeestr
  • 37
  • 7
  • 1
    Consider not using `Calendar`, `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated. Instead use `LocalDate` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Dec 02 '20 at 18:05

1 Answers1

0

Try using this

 long diff = System.currentTimeMillis() - calendar1.getTimeInMillis();

 dias.setText("" + TimeUnit.MILLISECONDS.toDays(diff));

Hope this helps. Feel free to ask for clarifications...

Vishnu
  • 663
  • 3
  • 7
  • 24
  • 1
    It will give wrong results in corner cases. `TimeUnit` assumes that a day is always 24 hours, but due to summer time (DST) and other time anomalies a day may be for example 23 or 25 hours long. – Ole V.V. Dec 02 '20 at 18:06
  • A better approach would use the modern *java.time* classes. – Basil Bourque Dec 05 '20 at 02:02