将字符串转换为日期并将其与 Java 中的 LocalDateTime.now() 进行比较

SNA*_*NAD -2 java android compare date

字符串数据位于之前以“Mon Jan 08 18:55:57 GMT+05:30 2024”格式存储的文件中。我使用以下代码来转换字符串以获取值“08 Jan 2024”

Boolean goahead = false;
SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");
SimpleDateFormat formatterOut = new SimpleDateFormat("dd MMM yyyy");
try {
  pundate = formatter.parse(punchDate);
  System.out.println(pundate);
  System.out.println(formatterOut.format(pundate));
} catch (ParseException e) {
   e.printStackTrace();
}

String convertedtodaydate = dateFormater(String.valueOf(LocalDateTime.now()), "dd MMM yyyy", "yyyy-MM-dd"); //Output is 16 Feb 2024

try {
   if(Objects.requireNonNull(sdf.parse(convertedtodaydate)).after(sdf.parse(formatterOut.format(pundate)))) {
     goahead = true;
   }
  } catch (ParseException e) {
            e.printStackTrace();
  }
Run Code Online (Sandbox Code Playgroud)

我得到的错误是

W/System.err: java.text.ParseException: Unparseable date: "16 Feb 2024"
Run Code Online (Sandbox Code Playgroud)

有没有更简单的方法来检查存储的日期是否早于当前日期?

Bas*_*que 6

永远不要使用有严重缺陷的遗留类,例如SimpleDateFormat, Date, Calendar。仅使用java.time类。

\n

永远不要打电话LocalDateTime.now。我无法想象这是最佳选择的场景。该类不能代表某个时刻,因为它缺少时区或偏移量的上下文。

\n
\n

字符串数据位于之前以“Mon Jan 08 18:55:57 GMT+05:30 2024”格式存储的文件中。

\n
\n

切勿使用本地化格式以文本方式存储日期时间值。仅使用ISO 8601格式进行数据存储和数据交换。

\n

使用 解析文本DateTimeFormatter

\n
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss OOOO uuuu" ).withLocale( Locale.US ) ;\nString input = "Mon Jan 08 18:55:57 GMT+05:30 2024" ;\nZonedDateTime zdt = ZonedDateTime.parse( input , f ) ;\n
Run Code Online (Sandbox Code Playgroud)\n

您只对日期部分感兴趣。

\n
LocalDate ld = zdt.toLocalDate();\n
Run Code Online (Sandbox Code Playgroud)\n

要生成标准ISO 8601格式的文本,请调用toString.

\n
String output = ld.toString() ;\n
Run Code Online (Sandbox Code Playgroud)\n

要生成自定义格式的文本,请定义另一个DateTimeFormatter.

\n
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd MMM uuuu" ).withLocale( Locale.US ) ;\nString output = ld.format( f ) ;\n
Run Code Online (Sandbox Code Playgroud)\n

您显然想要将存储的日期与今天\xe2\x80\x99s 的日期进行比较。要捕获当前日期,请指定时区。对于任何特定时刻,全球各地的日期因时区而异。日本东京位于 \xe2\x80\x9ctomorrow\xe2\x80\x9d,同时俄亥俄州托莱多位于 \xe2\x80\x9cyesterday\xe2\x80\x9d。

\n
ZoneId zKolkata = ZoneId.of( "Asia/Kolkata" ) ;\nLocalDate todayKolkata = LocalDate.now( zKolkata ) ;\nboolean isStoredDatePast = ld.isBefore( todayKolkata ) ;\n
Run Code Online (Sandbox Code Playgroud)\n

也许您确实想查看存储的时刻是否在当前时刻之前。

\n
boolean isStoredMomentPast = zdt.toInstant().isBefore( Instant.now() ) ;\n
Run Code Online (Sandbox Code Playgroud)\n

要计算以小时-分钟-秒为单位的经过时间,请使用Duration

\n
Duration elapsed = Duration.between ( zdt.toInstant() , Instant.now() ) ;\n
Run Code Online (Sandbox Code Playgroud)\n

对于以年-月-日为单位的经过时间,请使用Period.

\n

  • `Duration timeSince = Duration. Between(OffsetDateTime.parse(dateString, formatter), OffsetDateTime.now());` (2认同)