【问题标题】:Java : Date String to Hours [duplicate]Java:日期字符串到小时[重复]
【发布时间】:2020-07-26 20:36:06
【问题描述】:

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

那么这个操作是否有任何框架/工具。

String s1 = "2020-07-26T20:08:27Z";
String s2 = "2020-07-26T21:08:27Z";

在上面的示例代码中,我想找到更大的日期

【问题讨论】:

标签: java java-8 date


【解决方案1】:

tl;博士

Instant
.parse( "2020-07-26T20:08:27Z" ) 
.isBefore(
    Instant.parse( "2020-07-26T21:08:27Z" )
)

是的

java.time

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

ISO 8601

输入末尾的Z 表示offset-from-UTC 为零时分秒,或UTC 本身。 Z 发音为“祖鲁语”。

您的输入字符串采用标准ISO 8601 格式。 java.time 类在解析/生成字符串时默认使用这些格式。所以不需要指定格式模式。

Instant

Instant 对象代表 UTC 中的时刻。

Instant instantA = Instant.parse( "2020-07-26T20:08:27Z" ) ;
Instant instantB = Instant.parse( "2020-07-26T21:08:27Z" ) ;

使用equalsisBeforeisAfter进行比较。

boolean aBeforeB = instantA.isBefore( instantB ) ;

Duration

您可以将两个时刻之间经过的时间捕获为Duration 对象。

Duration d = Duration.between( instantA , instantB ) ;

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


【讨论】:

    【解决方案2】:

    为此使用 compareTo() 方法。 我有一个例子给你

          SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd");
      Date d1 = sdformat.parse("2019-04-15");
      Date d2 = sdformat.parse("2019-08-10");
      System.out.println("The date 1 is: " + sdformat.format(d1));
      System.out.println("The date 2 is: " + sdformat.format(d2));
      if(d1.compareTo(d2) > 0) {
         System.out.println("Date 1 occurs after Date 2");
      } else if(d1.compareTo(d2) < 0) {
         System.out.println("Date 1 occurs before Date 2");
      } else if(d1.compareTo(d2) == 0) {
         System.out.println("Both dates are equal");
      }
    

    【讨论】:

    • 仅供参考,存在严重缺陷的日期时间类,例如 java.util.Datejava.util.CalendarGregorianCalendarjava.text.SimpleDateFormat 现在是 legacy,被内置的 java.time 类所取代Java 8 及更高版本。建议在 2020 年使用它们是糟糕的建议。
    • 请不要教年轻人使用早已过时且臭名昭著的SimpleDateFormat类。至少不是第一选择。而且不是没有任何保留。今天我们在java.time, the modern Java date and time API, 和它的DateTimeFormatter 中做得更好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    相关资源
    最近更新 更多