Java:日期字符串转换为小时

huangapple go评论63阅读模式
英文:

Java : Date String to Hours

问题

以下是翻译好的内容:

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

那么是否有任何可以执行此操作的框架或工具呢?

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

在上面的示例代码中,我想要找出较大的日期。

英文:

i have this Date String 2020-07-26T20:08:27Z i want to perform date comparison.

so is there any framework/util for this operation.

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

in the above sample code, i want to find the bigger date

答案1

得分: 2

# tl;dr

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

> true


# *java.time*

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

## ISO 8601

您输入的末尾的 `Z` 表示零小时-分钟-秒的 [UTC 偏移][1],或者表示 [UTC][2] 本身。`Z` 发音为“Zulu”。

您的输入字符串采用标准的 [ISO 8601][3] 格式。*java.time* 类在解析/生成字符串时默认使用这些格式,因此无需指定格式化模式。

## `Instant`

[`Instant`][4] 对象表示 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`

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

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

您可以查询 `Duration` 对象是否为零或负值。

----------

如果您有任何其他需要翻译的内容,请随时提问。

英文:

tl;dr

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

>true

java.time

Use the modern java.time classes built into Java 8 and later.

ISO 8601

The Z on the end of your input indicates an offset-from-UTC of zero hours-minutes-seconds, or UTC itself. The Z is pronounced “Zulu”.

Your input strings are in standard ISO 8601 format. The java.time classes use these formats by default when parsing/generating strings. So no need to specify a formatting pattern.

Instant

An Instant object represents a moment in UTC.

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

Compare using equals, isBefore, isAfter.

boolean aBeforeB = instantA.isBefore( instantB ) ;

Duration

You can capture the time elapsed between the two moments as a Duration object.

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

You can ask the Duration object if it is zero or negative.


Java:日期字符串转换为小时

huangapple
  • 本文由 发表于 2020年7月27日 04:36:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/63105438.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定