如何检查字符串日期在今天?



>2019-12-07 20:13:04

我需要如果这个日期是今天,我的Buton可见性是可见的。

try {
String dtStart = sales.getDate();
SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
Date date = format.parse(dtStart);

Calendar now = Calendar.getInstance();
Date today = now.getTime();
if (date == today){
holder.delete.setVisibility(View.VISIBLE);
}else {
holder.delete.setVisibility(View.INVISIBLE);
}
} catch (ParseException e) {
e.printStackTrace();
}

使用 java-8 日期时间 API,首先你的格式化程序是错误的月份应该用大写字母MM表示,并使用 DateTimeFormatter 而不是旧版SimpleDateFormat

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

然后使用格式化程序将输入字符串解析为 LocalDateTime

String date = "2019-12-07 20:13:04";
LocalDateTime dateTime = LocalDateTime.parse(date,formatter);

最后使用equals将输入日期与当前日期进行比较,这是在 android 上获取 java-8 日期时间 API 的信息

dateTime.toLocalDate().equals(LocalDate.now());  //true

您可以使用DateUtils.isToday方法来检查日期是否为今天:

try {
String dtStart = sales.getDate();
SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
Date date = format.parse(dtStart);
boolean isToday = DateUtils.isToday(date.getTime());
if (isToday){
holder.delete.setVisibility(View.VISIBLE);
}else {
holder.delete.setVisibility(View.INVISIBLE);
}
} catch (ParseException e) {
e.printStackTrace();
}

如果您已经将日期字符串转换为日期,则可以将Date-Object 转换为Calendar-Object,并比较年、月和日。

实现示例:

private boolean isToday(Date date) {
Calendar calendar = Calendar.getInstance();
Calendar toCompare = Calendar.getInstance();
toCompare.setTimeInMillis(date.getTime());
return calendar.get(Calendar.YEAR) == toCompare.get(Calendar.YEAR)
&& calendar.get(Calendar.MONTH) == toCompare.get(Calendar.MONTH)
&& calendar.get(Calendar.DAY_OF_MONTH) == toCompare.get(Calendar.DAY_OF_MONTH);
}

或者,您可以将DateCalendar转换为毫秒,并与今天的毫秒进行比较。

实现示例:

private boolean isToday2(Date dateToCheck) {
Calendar calendar = Calendar.getInstance();
// you have to set calendar object to 00:00:00
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
// milliseconds of 1 day = 86400000
return dateToCheck.getTime() - calendar.getTimeInMillis() < 86400000; 
}

但是,这两种解决方案都无法正确处理本地化时间。因此,请谨慎使用。

我们可以使用Java 8 Date-Time api,如下所示:

LocalDate dt2= LocalDate.of(2019,10,20);
String dtStart= dt2.format(DateTimeFormatter.ISO_DATE);
LocalDate currentDt= LocalDate.now();
if(currentDt.format(DateTimeFormatter.ISO_DATE).equals(dtStart)) {
// logic here 
}else {
//logic here
}

最新更新