[英]Java JodaTime: “123” should be (long) 123. How can I do that without having “ms” for example at the end: “10ms”?
如何从Java-JodaTime格式化PeriodFormatter以处理类似以下的字符串:
“ 10s” =(长)10000; <-我解决了。
“ 10ms” =(长)10。
“ 10” =长10。<-仅这是我的问题!
我可以通过此链接使用Joda Time处理前两个命令:
解析时间字符串,例如“ 1h 30min”
但是我的问题是:如何将“ 10”转换为毫厘克。 没有空的追加?
PeriodFormatter formatter = new PeriodFormatterBuilder()
.appendSeconds().appendSuffix("s")
.appendMillis().appendSuffix("ms")
.append###########().appendSuffix("") // <--here is my problem. Keep it empty won't work: InvalidFormatException
.toFormatter();
Period p = formatter.parsePeriod("10s"); // <-- this works
p = formatter.parsePeriod("10"); // <-- Here is my problem. It should be 10 millisec.
System.out.println("Time in millisec.: "+p.getMillis());
我在文档或Google中找不到任何内容。 因此,感谢您的帮助。
作为一种解决方法,我使用Joda-Code上方的正则表达式来捕获内部仅包含数字的字符串:
if (time.matches("[0-9]+")) {
return Long.parseLong(time);
}
PeriodFormatter formatter = new PeriodFormatterBuilder()
.appendWeeks().appendSuffix("w")
.appendDays().appendSuffix("d")
.appendHours().appendSuffix("h")
.appendMinutes().appendSuffix("m")
.appendSeconds().appendSuffix("s")
.appendMillis().appendSuffix("ms")
.toFormatter();
return p.toStandardDuration().getMillis();
如果输入不包含文字,则只需将其从构建器模式中删除即可。 因此,使用以下简单代码即可解决仅将数字解析为毫秒的问题:
PeriodFormatter pf = new PeriodFormatterBuilder()
.appendMillis()
.toFormatter();
Period p = pf.parsePeriod("10");
System.out.println("Time in millisec.: " + p);
// Time in millisec.: PT0.010S
System.out.println("Time in millisec.: " + p.getMillis());
// Time in millisec.: 10
这里是没有regexp的解决方案:
PeriodFormatter f = new PeriodFormatterBuilder()
.appendSeconds().appendSuffix("s")
.appendMillis().appendSuffix("ms")
.appendMillis()
.toFormatter();
老实说,这有点"1s10ms10"
,而且还会解析一个像"1s10ms10"
这样的字符串,这很尴尬,但是这是您不应该遇到的边缘情况,更重要的是,它将实现您想要的。 将正确评估以下字符串: "1s10ms"
, "1s"
, "10ms"
, "10"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.