【问题标题】:How to calculate the number of days between two dates selected through date Picker in android如何计算通过Android中的日期选择器选择的两个日期之间的天数
【发布时间】:2020-05-03 13:14:34
【问题描述】:

我想计算从日期选择器中选择的日期之间的天数。我已经尝试了足够多,但找不到任何解决方案!请帮我找到解决方案。这是当我们单击editText 时显示日期选择器的代码。我到处搜索,但找不到任何合适的结果。

离开活动.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>

【问题讨论】:

    标签: java android datepicker androidx datepickerdialog


    【解决方案1】:

    使用以下函数计算两个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;
    }
    

    【讨论】:

    • 如何自动计算天数并显示在 textView 中。如何使用监听器
    • 当使用输入两个日期时调用此函数并显示结果
    【解决方案2】:

    永远不要使用Calendar。它在几年前被 JSR 310 中定义的现代 java.time 类所取代。

    对于没有时间和时区的日期值,使用LocalDate

    我不懂安卓。但是你似乎从你的选择器中得到了年、月和日的整数。制作LocalDate 对象。

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

    计算经过的天数。

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

    关于java.time

    java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.DateCalendarSimpleDateFormat

    要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310

    Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。

    您可以直接与您的数据库交换 java.time 对象。使用符合JDBC 4.2 或更高版本的JDBC driver。不需要字符串,不需要java.sql.* 类。 Hibernate 5 和 JPA 2.2 支持 java.time

    从哪里获得 java.time 类?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-25
      • 1970-01-01
      • 1970-01-01
      • 2017-03-07
      • 2015-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多