javajodatime:“123”应该是(长)123。如果结尾没有“ms”,例如“10ms”,我怎么能做到这一点?
如何从Java JodaTime格式化PeriodFormatter以处理以下字符串:javajodatime:“123”应该是(长)123。如果结尾没有“ms”,例如“10ms”,我怎么能做到这一点?,java,jodatime,periodformatter,Java,Jodatime,Periodformatter,如何从Java JodaTime格式化PeriodFormatter以处理以下字符串: 10s=长10000 如果输入不包含文本,那么只需将其从构建器模式中删除即可。因此,使用以下简单代码可以解决仅解析一个数到毫秒的问题: PeriodFormatter pf = new PeriodFormatterBuilder() .appendMillis() .toFormatter(); Period p = pf.parsePeriod("10");
10s=长10000 如果输入不包含文本,那么只需将其从构建器模式中删除即可。因此,使用以下简单代码可以解决仅解析一个数到毫秒的问题:
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这样的字符串,这很尴尬,但这是一个边缘情况,您不应该遇到,更重要的是,这将实现您想要的。将正确计算以下字符串:1s10ms、1s、10ms、10尝试以下操作:.appendMillis.appendSuffixms,这是一个好主意,但会导致错误:格式无效。错误出现在formatter.10;你能试着删除.appendSuffix吗?不,因为我需要两个:10毫秒和10毫秒:-这样就完成了。我在Joda代码上方使用正则表达式,请参见上文。但如果你有Joda的解决方案,我会更高兴,因为它更干净。甚至,是个好主意。但我认为它只能工作10或10毫秒。但我同时需要:.appendSeconds.appendSuffix.appendMillis.appendMillis.appendSuffix。在这段代码中,我遇到了一个错误:无效格式10ms在ms.@AlexHH处格式不正确,那么您应该在两个句点格式化程序中定义两种不同的模式,并尝试每种模式来解析您的输入。甚至可能有3种不同的模式?!哦,那么在我的Joda代码上面使用正则表达式就更干净了。我在上面的问题中插入了它。谢谢你的帮助!很抱歉,在我提出问题之前,我没有找到解决办法。谢谢,拉泽尔。它向我抛出了一个非法的ArgumentException:InvalidFormat 12345ms在s处的格式不正确。因此,他知道分钟的m,但不知道ms。只有当我删除.appendMillis.appendsuffix行时,它才有效。但是他也不认识那位女士嗯。。。这很棘手。在第一次分析中,我想问题在于m与ms被混淆了。我假设最后一个元素被特别处理,比如:如果所有的字符串都被读取了,那么优先考虑最后一个元素。。。好吧,如果你有什么想法,我会告诉你的
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
PeriodFormatter f = new PeriodFormatterBuilder()
.appendSeconds().appendSuffix("s")
.appendMillis().appendSuffix("ms")
.appendMillis()
.toFormatter();