英文:
How to calculate the number of days between two dates selected through date Picker in android
问题
以下是翻译后的内容:
我想要计算从日期选择器中选择的日期之间的天数。我已经尝试了很多次,但是找不到任何解决方案!请帮助我找到解决方案。以下是在点击编辑文本时显示日期选择器的代码。我已经到处搜索了,但是找不到合适的结果。
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;
@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);
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="申请请假"
android:textSize="24sp"
android:layout_gravity="center"
android:textStyle="bold"
android:background="@drawable/editt_text_background" />
</LinearLayout>
<!-- TODO: 更新空白片段布局 -->
<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="选择请假类型"
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>
</ScrollView>
</LinearLayout>
请注意,代码中的注释部分(// 和 )没有被翻译,因为它们是对代码的说明,而不是实际的翻译内容。如果您需要进一步的帮助,请随时提问。
英文:
I want to calculate the number of days between the dates selected from date picker. Ive tried enough but couldn't find any solution! Please help me find the solution. This is the code for displaying datepicker when we click the editText. I have searched everywhere but couldn't find any proper results.
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>
答案1
得分: 0
使用以下函数来计算两个 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;
}
英文:
Use following function to count diference of days between two Date
, you can also use same for calculating difrence of Hours, Minutes or Seconds by just change the return object.
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;
}
答案2
得分: 0
不要使用 Calendar
。它已经被现代的 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教程。并在Stack Overflow上搜索许多示例和解释。规范是 JSR 310。
Joda-Time 项目,现在处于维护模式,建议迁移到 java.time 类。
您可以直接与数据库交换 java.time 对象。使用与JDBC 4.2或更高版本兼容的JDBC驱动程序。无需字符串,也无需 java.sql.*
类。Hibernate 5 和 JPA 2.2 支持 java.time。
在哪里获取 java.time 类?
- Java SE 8、Java SE 9、Java SE 10、Java SE 11和更高版本 - 作为标准Java API的一部分,带有捆绑的实现。
- Java 9添加了一些小的功能和修复。
- Java SE 6 和 Java SE 7
- 大多数 java.time 功能已经在 ThreeTen-Backport 中向Java 6和7回溯。
- Android
- Android的较新版本捆绑了 java.time 类的实现。
- 对于较早版本的Android(<26),ThreeTenABP 项目适配了ThreeTen-Backport(如上所述)。请参阅如何使用ThreeTenABP…。
英文:
Never use Calendar
. It was years ago supplanted by the modern java.time classes defined in JSR 310.
For date values without time of day and without time zone, use LocalDate
.
I do not know Android. But you seem to be getting the year, month, and day as integers from your picker. Make LocalDate
objects of those.
LocalDate localDate = LocalDate.of( y , m , d ) ;
Calculate elapsed days.
long days = ChronoUnit.DAYS.between( start , end ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
- Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and Java SE 7
- Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.time classes.
- For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
专注分享java语言的经验与见解,让所有开发者获益!
评论