gpt4 book ai didi

java - 使用 Java Calendar (Android) 确定给定字符串时间是否过去

转载 作者:行者123 更新时间:2023-12-01 17:52:06 24 4
gpt4 key购买 nike

我正在尝试编写“isPast(String dateStr)”函数,该函数接收日期字符串,如果是过去的则返回 true,否则返回 false。

private static boolean isPast(String dateStr) {
Calendar c = GregorianCalendar.getInstance();

int currentYear = c.get(Calendar.YEAR);
int currentMonth = c.get(Calendar.MONTH);
int currentDay = c.get(Calendar.DAY_OF_MONTH);
int currentHour = c.get(Calendar.HOUR_OF_DAY);
int currentMinute = c.get(Calendar.MINUTE);
c.set(currentYear, currentMonth, currentDay, currentHour, currentMinute);
Date now = c.getTime();

SimpleDateFormat sdfDates = new SimpleDateFormat("dd/m/yyyy");

Date date = null;
try {
date = sdfDates.parse(dateStr);

} catch (ParseException e) {
e.printStackTrace();
}

if (now.compareTo(date) == 1){
System.out.println(dateStr + " date given is past");
return true;
}
System.out.println(dateStr + " date given is future");
return false;
}

我用以下方式调用它:

 String str1 = "22/04/2018";
String str2 = "22/01/2018";
System.out.println(isPast(str1));
System.out.println(isPast(str2));

输出是:

22/04/2018 date given is past
22/01/2018 date given is past

这是怎么回事?这不是真的。我在这个问题上花了太长时间 - 它应该很简单,显然我错过了日历对象的一些东西......

最佳答案

使用 Java 8 中提供的 LocalDate

  public static void main(String[] args) {

String str1 = "22/04/2018";
String str2 = "22/01/2018";
System.out.println(isPast(str1));
System.out.println(isPast(str2));
}


private static boolean isPast(String dateStr) {

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate dates = LocalDate.parse(dateStr, formatter);

return dates.isBefore(LocalDate.now());
}

关于java - 使用 Java Calendar (Android) 确定给定字符串时间是否过去,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48938224/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com