我有一个日期选择器,通过它我可以在字符串中设置日期,即 mDate。 现在要设置时间,我想检查当前日期和 mDate 是否相同,如果它们相同,我想将 minTime 设置为 TimePicker 对话框,如果它们不同,则不应将 min time 设置为时间。
如果 mDate 为空,则时间仍应显示所有时间。
mEditTxt_Time.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Date date = null;
try {
if(!mDate.equals("")) {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
date = format.parse(mDate);
}
Calendar compareDate = Calendar.getInstance();
compareDate.getTime();
Calendar now = Calendar.getInstance();
TimePickerDialog tpd = TimePickerDialog.newInstance(
PostShippingFragment.this,
now.get(Calendar.HOUR_OF_DAY),
now.get(Calendar.MINUTE),
true
);
if(date!=null) {
if (date.compareTo(compareDate.getTime())) {
tpd.setMinTime(now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE), now.get(Calendar.SECOND));
}
}
else {
tpd.setVersion(TimePickerDialog.Version.VERSION_2);
tpd.setAccentColor(ContextCompat.getColor(getActivity(), R.color.colorAccent));
tpd.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialogInterface) {
Log.d("TimePicker", "Dialog was cancelled");
}
});
tpd.show(getFragmentManager(), "Timepickerdialog");
}
}
catch (ParseException e)
{
Log.e("exception",e.toString());
}
}
});
我尝试过这个,但无法进行比较。
请帮忙。谢谢。
最佳答案
您可以使用 Date 的 compareTo()
方法。
它将返回一个整数值,
- 如果参数日期(compareDate)等于此日期,则返回值0;
- 如果此日期早于日期参数 (compareDate),则返回一个小于 0 的值;
- 如果此日期晚于该日期,则返回一个大于 0 的值 参数(比较日期)。
因此,如果您想检查两个日期是否相同,则需要如下修改 if 条件
。
if (date.compareTo(compareDate.getTime()) == 0) {
关于java - 如何将日期字符串与当前日期进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44515619/