>我有一个string s="2020-04-07T13:43:49-05:00"
我必须检查它是否大于当前日期,我尝试使用即时日期
Instant timestamp = Instant.parse(string);
但是没有用,我尝试了LocalDate
LocalDate date = LocalDate.parse(string, format);
这也不起作用,如何解析和检查
您应该将其解析为 OffsetDateTime,因为日期字符串具有偏移量
ISO-8601 日历系统中与 UTC/格林威治有偏移量的日期时间,例如 2007-12-03T10:15:30+01:00。
String s="2020-04-07T13:43:49-05:00";
OffsetDateTime dateTime = OffsetDateTime.parse(s);
然后通过转换为本地日期时间来检查天气是否大于 isBefore 或 isAfter
LocalDateTime.now().isBefore(dateTime.toLocalDateTime())
您还可以使用isBefore
和isAfter
直接比较OffsetDateTime
OffsetDateTime.now().isBefore(dateTime)
这对我来说使用 Java (jshell
( 13 工作正常:
jshell> import java.time.Instant
jshell> Instant.parse("2020-04-07T13:43:49-05:00")
$2 ==> 2020-04-07T18:43:49Z
为此使用 SimpleDateFormat。获取字符串并将其格式化为日期,然后检查它。
Date date= new Date();
String targetDate="2020-04-07 13:43:49";
Date date2= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(targetDate);
现在,您只需通过以下方式检查两个日期
if(date.getTime()>date2.getTime())
如果你想以相反的方式做,你也可以这样做。
Date date= new Date();
String currentDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date)
现在只需使用 if 条件检查两个字符串。