我将一些持续时间值存储在属性中,例如“ period:30s”或“ period:15m”,然后在我的方法中将其转换为毫秒。 从这种格式到millis是否有Java内置的映射器?
例如:
long millis = mapToMillis("15s") // millis variable should be 15000 here
long milllis2 = mapToMillis("1m") // millis2 variable shoul be 60000 here
我在Duration类中寻找了这样的映射器,但是没有一个匹配我的问题。
答案 0 :(得分:1)
Duration.parse()
确实提供了此功能。 documentation中提到了操作方法。您只需要按照此处提到的格式存储值。
示例:
System.out.println(
Duration.parse("PT15S").toMillis()
);
打印15000
。
如果需要处理日期而不是时间,可以在Period
类中使用等效的解析方法。
答案 1 :(得分:0)
如果您确定持续时间值为基于时间的金额(即秒,分钟,天,...),则可以使用Duration
类型。
使用方法
private static long mapToMillis(String duration) {
return Duration.parse("PT" + duration).toMillis();
}
代码段
long millis = mapToMillis("15s"); // millis variable should be 15000 here
long milllis2 = mapToMillis("1m"); // millis2 variable shoul be 60000 here
System.out.println(millis);
System.out.println(milllis2);
打印出
15000
60000