Java 自定义日期参数输入

Java Custom Date Argument Input

我目前正在编写一个 Spigot/Craftbukkit plugin 来管理禁令。在一种方法中,我有 TempBan Command Executor。我的目标是让用户使用自定义 "shorthand" 格式指定禁令持续时间。 例如:/tempban MyUser 5d2w My Reason"

我希望在毫秒内解析并返回字符串 5d2w。我试过自己做,但不可靠,只支持一种时间格式。所以你不能做组合。是否有使用 JodaTimeJava's default date format class 来完成此操作的高效方法?谢谢!

tl;博士

Duration.parse( "PT1H30M" ).toMillis()

ISO 8601

无需发明您自己的自定义 shorthand 格式。 ISO 8601 standard already defines a similar format for durations

模式 PnYnMnDTnHnMnS 使用 P 标记开始,使用 T 将任何年-月-日部分与任何时-分-秒部分分开。

示例:

  • 一个半小时是 PT1H30M
  • P3Y6M4D表示“三年六个月四天”。

java.time

java.time classes 在 parsing/generating 字符串时默认使用 ISO 8601 格式。这包括 Period and Duration class 用于表示未附加到时间轴的时间跨度的元素。

Duration

Duration d = Duration.ofHours( 1 ).plusMinutes( 30 );
String output = d.toString();

PT1H30M

并解析。

Duration d2 = Duration.parse( "PT1H30M" );

您可以要求总毫秒数的持续时间。

long millis = d2.toMillis();

5400000

参见 live code in IdeOne.com

但请记住 java.time classes 具有更精细的分辨率,纳秒级。所以你可能会在要求毫秒时丢失数据。

此外,我强烈建议您坚持使用 java.time 对象和 ISO 8601 字符串,并且 避免将日期时间值表示为毫秒计数 等.

Period

对于年-月-日,使用 Period class。

Period p = Period.parse( "P3Y6M4D" );

……和……

String output = p.toString();

P3Y6M4D

请注意此 class 上的 normalized 方法。例如,“1 年 15 个月”的时间段将标准化为“2 年 3 个月”。

另请注意,Period 建立在 LocalDate 信息之上。因此,它没有时区的概念,也没有任何关于夏令时 (DST) 等异常的想法。

这个 class 可以解决一整天的问题。所以 class 没有提供明确的方法来计算毫秒数。


关于java.time

java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

要了解更多信息,请参阅 Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310

从哪里获得java.time classes?

  • Java SE 8 and SE 9 及更高版本
    • 内置。
    • 标准 Java API 的一部分,带有捆绑实施。
    • Java 9 添加了一些小功能和修复。
  • Java SE 6 and SE 7
  • Android
    • ThreeTenABP 项目专门为 Android 改编 ThreeTen-Backport(如上所述)。
    • 参见

ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.