如何在java中解析基于时间的令牌?(1m 1M 1d 1Y 1W 1S)

gst*_*low 4 java datetime duration localdate

我从 FE 得到以下字符串:

1m
5M
3D
30m
2h
1Y
3W
Run Code Online (Sandbox Code Playgroud)

它对应于 1 分钟、5 个月、3 天、30 分钟、2 小时、1 年、3 周。

java中有没有解析它的意思?

我想用 Instant(或 LocalDatetTime)操作(加/减)。有没有办法在java中做到这一点?

Ole*_*.V. 5

Period & Duration

我认为以下解决方案简单且非常通用(不完全通用)。

public static TemporalAmount parse(String feString) {
    if (Character.isUpperCase(feString.charAt(feString.length() - 1))) {
        return Period.parse("P" + feString);
    } else {
        return Duration.parse("PT" + feString);
    }
}
Run Code Online (Sandbox Code Playgroud)

看来你的基于日期的单位(年,月,周,日)被标以大写字母缩写(YMWD而基于时间的(小时和分钟)都是小写()hm)。所以我测试了字符串最后一个字符的大小写来决定是解析成 aPeriod还是 a Duration。我利用了Period.parse和 都Duration.parse接受这两种情况下的字母这一事实。

你想持续时间增加或减少往返InstantLocalDateTime。这在大多数情况下都有效。让我们来看看:

    String[] timeAmountStrings = { "1m", "5M", "3D", "30m", "2h", "1Y", "3W" };
    LocalDateTime base = LocalDateTime.of(2019, Month.MARCH, 1, 0, 0);
    for (String tas : timeAmountStrings) {
        TemporalAmount amount = parse(tas);
        System.out.println("String: " + tas + " parsed: " + amount + " added: " + base.plus(amount));

        try {
            System.out.println("Added to Instant: " + Instant.EPOCH.plus(amount));
        } catch (DateTimeException dte) {
            System.out.println("Adding to Instant didn’t work: " + tas + ' ' + dte);
        }

        System.out.println();
    }
Run Code Online (Sandbox Code Playgroud)

输出:

String: 1m parsed: PT1M added: 2019-03-01T00:01
Added to Instant: 1970-01-01T00:01:00Z

String: 5M parsed: P5M added: 2019-08-01T00:00
Adding to Instant didn’t work: 5M java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Months

String: 3D parsed: P3D added: 2019-03-04T00:00
Added to Instant: 1970-01-04T00:00:00Z

String: 30m parsed: PT30M added: 2019-03-01T00:30
Added to Instant: 1970-01-01T00:30:00Z

String: 2h parsed: PT2H added: 2019-03-01T02:00
Added to Instant: 1970-01-01T02:00:00Z

String: 1Y parsed: P1Y added: 2020-03-01T00:00
Adding to Instant didn’t work: 1Y java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Years

String: 3W parsed: P21D added: 2019-03-22T00:00
Added to Instant: 1970-01-22T00:00:00Z
Run Code Online (Sandbox Code Playgroud)

我们看到添加到LocalDateTime在所有情况下都有效。Instant在大多数情况下添加到作品中,只有我们不能添加几个月或几年的时间。