[英]Java JodaTime: “123” should be (long) 123. How can I do that without having “ms” for example at the end: “10ms”?
How do I format the PeriodFormatter from Java-JodaTime to handle Strings like: 如何从Java-JodaTime格式化PeriodFormatter以处理类似以下的字符串:
"10s" = (long) 10000; “ 10s” =(长)10000; <-- I solved that. <-我解决了。
"10ms" = (long) 10. “ 10ms” =(长)10。
"10" = long 10. <-- Only here is my problem! “ 10” =长10。<-仅这是我的问题!
I can handle the first two commands with Joda Time with this link: 我可以通过此链接使用Joda Time处理前两个命令:
Parsing time strings like "1h 30min" 解析时间字符串,例如“ 1h 30min”
But my problem: How can I convert the "10" to millisec. 但是我的问题是:如何将“ 10”转换为毫厘克。 without an empty appending? 没有空的追加?
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());
I could not find anything in the doc or at Google. 我在文档或Google中找不到任何内容。 So thanks for your help. 因此,感谢您的帮助。
As a workaround I am using a regular expression above of the Joda-Code to catch strings with only digits inside: 作为一种解决方法,我使用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();
If the input does not contain a literal then simply leave it out from your builder-pattern. 如果输入不包含文字,则只需将其从构建器模式中删除即可。 So parsing only a number to milliseconds can be solved with following simple code: 因此,使用以下简单代码即可解决仅将数字解析为毫秒的问题:
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
Here a solution without regexp: 这里是没有regexp的解决方案:
PeriodFormatter f = new PeriodFormatterBuilder()
.appendSeconds().appendSuffix("s")
.appendMillis().appendSuffix("ms")
.appendMillis()
.toFormatter();
To be honest, this a bit of an hack and will also parse a string like "1s10ms10"
which is awkward, BUT this an edge case that you should not encounter and, more importantly, will achieve what you want. 老实说,这有点"1s10ms10"
,而且还会解析一个像"1s10ms10"
这样的字符串,这很尴尬,但是这是您不应该遇到的边缘情况,更重要的是,它将实现您想要的。 The following strings will be correctly evaluated: "1s10ms"
, "1s"
, "10ms"
, "10"
将正确评估以下字符串: "1s10ms"
, "1s"
, "10ms"
, "10"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.