Как рассчитать количество дней между двумя датами, выбранными через указатель даты в android - PullRequest
0 голосов
/ 03 мая 2020

Я хочу рассчитать количество дней между датами, выбранными в окне выбора даты. Я попробовал достаточно, но не смог найти никакого решения! Пожалуйста, помогите мне найти решение. Это код для отображения даты выбора, когда мы нажимаем editText. Я искал везде, но не смог найти правильных результатов.

LeaveActivity. java

    public class LeaveActivity extends AppCompatActivity {

    private static EditText edt_tofrom;
    private static EditText edt_toDate;
    private TextView no_ofDays;

    private DatePickerDialog.OnDateSetListener edt_tofromlistener;
    private DatePickerDialog.OnDateSetListener edt_toDatelistener;


//    DatePickerDialogFragment mDatePickerDialogFragment;

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

        edt_tofrom = (EditText) findViewById(R.id.from_date);
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
//        edt_toform.setText( sdf.format(Calendar.getTime()));
        edt_toDate = (EditText) findViewById(R.id.to_date);
        no_ofDays = (TextView) findViewById(R.id.edt_noOfDays);
//        mDatePickerDialogFragment = new DatePickerDialogFragment();


//        edt_toform.setOnClickListener(this);
//        edt_toDate.setOnClickListener(this);

        edt_tofrom.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);
                int day1 = calendar.get(Calendar.DAY_OF_YEAR);

                DatePickerDialog datePickerDialog = new DatePickerDialog(LeaveActivity.this,
                        edt_tofromlistener, year, month, day);

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

        edt_tofromlistener = 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 + "");
                String date1 = +year + "/" + month + "/" + dayOfMonth + "";
                edt_tofrom.setText(date1);

            }
        };

        edt_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);
                int day2 = calendar.get(Calendar.DAY_OF_YEAR);

                DatePickerDialog datePickerDialog = new DatePickerDialog(LeaveActivity.this,
                        edt_toDatelistener, year, month, day);

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


            }
        });

        edt_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 + "");

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

            }

        };

    }


}

activity_leave. xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp"

    tools:context=".activities.LeaveActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="APPLY FOR LEAVE"
            android:textSize="24sp"
            android:layout_gravity="center"
            android:textStyle="bold"
            android:background="@drawable/editt_text_background"/>

    </LinearLayout>


    <!-- TODO: Update blank fragment layout -->


    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:background="@drawable/editt_text_background">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:orientation="horizontal"
                android:layout_weight="1">

                <TextView
                    android:id="@+id/selectTxtView"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="10dp"
                    android:layout_marginTop="10dp"
                    android:layout_marginEnd="10dp"
                    android:layout_marginBottom="10dp"
                    android:padding="10dp"
                    android:text="Select Leave Type"
                    android:textSize="15sp"
                    android:textStyle="bold"/>

                <Spinner
                    android:id="@+id/spinner"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="10dp"
                    android:layout_toEndOf="@id/selectTxtView"
                    android:background="@drawable/editt_text_background"
                    android:entries="@array/LeaveType"
                    android:padding="10dp" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:orientation="horizontal"
                android:padding="10dp"
                android:layout_weight="1">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="From Date:"
                    android:textColor="#000000"/>

                <EditText
                    android:id="@+id/from_date"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:ems="10"
                    android:layout_weight="1"
                    android:background="@drawable/editt_text_background"
                    android:clickable="true"
                    android:longClickable="false"
                    android:inputType="date"
                    android:layout_marginStart="36dp"
                    android:layout_marginEnd="20dp"
                    android:focusable="false"/>



                <!--            <DatePicker-->
                <!--                android:id="@+id/date_picker"-->
                <!--                android:layout_width="wrap_content"-->
                <!--                android:layout_height="wrap_content"-->
                <!--                android:calendarViewShown="false"-->
                <!--                android:datePickerMode="spinner"/>-->

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:padding="10dp">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:text="To Date:"
                    android:textColor="#000000"/>

                <EditText
                    android:id="@+id/to_date"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:ems="10"
                    android:background="@drawable/editt_text_background"
                    android:clickable="true"
                    android:longClickable="false"
                    android:inputType="date"
                    android:layout_marginStart="36dp"
                    android:layout_marginEnd="20dp"
                    android:focusable="false" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:padding="10dp"
                android:layout_weight="1">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="No.Of Days:"
                    android:textColor="#000"
                    android:padding="10dp"/>
                <TextView
                    android:id="@+id/edt_noOfDays"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="@drawable/editt_text_background"/>
            </LinearLayout>

      </ScrollView>

 </LinearLayout>

Ответы [ 2 ]

0 голосов
/ 03 мая 2020

Никогда не используйте Calendar. Это были годы go, вытесненные современными java .time классами, определенными в JSR 310.

Для значений даты без времени дня и без часового пояса используйте LocalDate ,

Не знаю Android. Но вы, кажется, получаете год, месяц и день в виде целых чисел от вашего сборщика. Сделай из них LocalDate предметов.

LocalDate localDate = LocalDate.of( y , m , d ) ;

Рассчитать прошедшие дни.

long days = ChronoUnit.DAYS.between( start , end ) ;

О java .time

Фреймворк java .time встроен в Java 8 и более поздние версии. Эти классы вытесняют проблемные старые устаревшие классы даты и времени, такие как java.util.Date, Calendar, & SimpleDateFormat.

Чтобы узнать больше, см. Учебник Oracle . И поиск переполнения стека для многих примеров и объяснений. Спецификация: JSR 310 .

Проект Joda-Time , теперь в режиме обслуживания , рекомендует перейти на java .time классов.

Вы можете обмениваться java .time объектами непосредственно с вашей базой данных. Используйте драйвер JDB C , совместимый с JDB C 4.2 или более поздней версией. Нет необходимости в строках, нет необходимости в java.sql.* классах. Поддержка Hibernate 5 и JPA 2.2 java .time .

Где взять java .time классы?

  • Java SE 8 , Java SE 9 , Java SE 10 , Java SE 11 и более поздних версий - часть стандартного API Java со связанной реализацией.
    • Java 9 добавляет некоторые незначительные функции и исправления.
  • Java SE 6 и Java SE 7
    • Большинство функций java .time перенесено на Java 6 & 7 в ThreeTen-Backport .
  • Android
    • Более поздние версии Android комплектных реализаций классов java .time .
    • Для более ранних Android (<26) <a href="https://github.com/JakeWharton/ThreeTenABP" rel="nofollow noreferrer"> ThreeTenABP проект адаптируется ThreeTen-Backport (упомянуто выше). См. Как использовать ThreeTenABP… .

Table of which java.time library to use with which version of Java or Android

0 голосов
/ 03 мая 2020

Используйте следующую функцию для подсчета разности дней между двумя Date, вы также можете использовать ее для вычисления разности часов, минут или секунд, просто изменив возвращаемый объект.

public static Long getDateDifferenceInDays(Date startDate, Date endDate) {

    Long different = endDate.getTime() - startDate.getTime();

    Long secondsInMilli = 1000L;
    Long minutesInMilli = secondsInMilli * 60;
    Long hoursInMilli = minutesInMilli * 60;
    Long daysInMilli = hoursInMilli * 24;

    Long elapsedDays = different / daysInMilli;
    different = different % daysInMilli;

    Long elapsedHours = different / hoursInMilli;
    different = different % hoursInMilli;

    Long elapsedMinutes = different / minutesInMilli;
    different = different % minutesInMilli;

    Long elapsedSeconds = different / secondsInMilli;

    System.out.printf("%d days, %d hours, %d minutes, %d seconds%n", elapsedDays, elapsedHours, elapsedMinutes, elapsedSeconds);

    return elapsedDays;
}
...