Java:日期字符串到小时

Java:日期字符串到小时,java,java-8,date,Java,Java 8,Date,我有这个日期字符串2020-07-26T20:08:27Z我想执行日期比较 那么这个操作是否有任何框架/util String s1 = "2020-07-26T20:08:27Z"; String s2 = "2020-07-26T21:08:27Z"; 在上面的示例代码中,我想找到更大的日期 为此,请使用compareTo()方法。 我给你举个例子 SimpleDateFormat sdformat=新的SimpleDateFormat(“yyyy-

我有这个日期字符串
2020-07-26T20:08:27Z
我想执行日期比较

那么这个操作是否有任何框架/util

String s1 = "2020-07-26T20:08:27Z";
String s2 = "2020-07-26T21:08:27Z";
在上面的示例代码中,我想找到更大的日期

为此,请使用compareTo()方法。 我给你举个例子

SimpleDateFormat sdformat=新的SimpleDateFormat(“yyyy-MM-dd”);
日期d1=sdformat.parse(“2019-04-15”);
日期d2=sdformat.parse(“2019-08-10”);
System.out.println(“日期1为:”+sdformat.format(d1));
System.out.println(“日期2是:“+sdformat.format(d2));
如果(d1.与(d2)相比>0){
System.out.println(“日期1发生在日期2之后”);
}否则,如果(d1.与(d2)相比<0){
System.out.println(“日期1发生在日期2之前”);
}如果(d1.与(d2)==0相比){
System.out.println(“两个日期相等”);
}
tl;博士 真的

java.time 使用java 8及更高版本中内置的现代java.time类

ISO 8601 输入端的
Z
表示零小时分秒或其本身。
Z
发音为“Zulu”

您的输入字符串是标准格式的。默认情况下,java.time类在解析/生成字符串时使用这些格式。因此,无需指定格式化模式

Instant
对象表示UTC中的某个时刻

Instant instantA = Instant.parse( "2020-07-26T20:08:27Z" ) ;
Instant instantB = Instant.parse( "2020-07-26T21:08:27Z" ) ;
使用
equals
isBefore
isAfter
进行比较

boolean aBeforeB = instantA.isBefore( instantB ) ;
持续时间
您可以将这两个时刻之间经过的时间捕获为对象

您可以询问
Duration
对象它是零还是负



在此处使用LocalDateTime@swordbeta No,而不是
LocalDateTime
。注意末尾的
Z
。这意味着UTC。因此,
Instant
OffsetDateTime
类适用。仅供参考,有严重缺陷的日期时间类,如,
Gregoriacalendar
java.text.SimpleDateFormat
现在被java 8和更高版本中内置的类所取代。建议在2020年使用它们是一个糟糕的建议。请不要教年轻人使用早已过时且臭名昭著的麻烦
SimpleDateFormat
class。至少不是第一个选择。而且不是毫无保留的。今天,我们在及其
DateTimeFormatter
中有了更好的功能。
Instant instantA = Instant.parse( "2020-07-26T20:08:27Z" ) ;
Instant instantB = Instant.parse( "2020-07-26T21:08:27Z" ) ;
boolean aBeforeB = instantA.isBefore( instantB ) ;
Duration d = Duration.between( instantA , instantB ) ;