我得到以下从FE字符串:
1m
5M
3D
30m
2h
1Y
3W
它对应于1分钟,5个月,3天,30分钟,2小时,1年,3周。
有没有意思在Java解析呢?
我想操纵(加/减)与即时(或LocalDatetTime)。有没有办法做到这一点在Java中?
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);
}
}
看来你的基于日期的单位(年,月,周,日)被标以大写字母缩写(Y
,M
,W
和D
而基于时间的(小时和分钟)都是小写()h
和m
)。所以我测试字符串的最后一个字符的情况来决定是否解析为一个Period
或一个Duration
。我利用的事实,两者Period.parse
并Duration.parse
接受在两种情况下的字母。
你想持续时间增加或减少往返Instant
或LocalDateTime
。这适用于大多数情况下。让我们来看看:
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();
}
输出:
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
我们看到,增加LocalDateTime
在所有情况下的作品。添加到Instant
在大多数情况下的作品,只有我们不能添加数月或数年给它的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句