为什么这输入了Joda Time周期构造的无效格式?

发布于 2025-02-03 06:24:29 字数 720 浏览 3 评论 0原文

我正在尝试将字符串如1H 30M 5S5M38S或 1H 3S 总时间为几秒钟。因此,例如,1m 20s将使整数值80秒为80秒。

我使用的是Joda时间:

PeriodFormatter formatter = new PeriodFormatterBuilder()
        .appendDays().appendSuffix("d").appendSeparatorIfFieldsAfter(" ")
        .appendHours().appendSuffix("h").appendSeparatorIfFieldsAfter(" ")
        .appendMinutes().appendSuffix("m").appendSeparatorIfFieldsAfter(" ")
        .appendSeconds().appendSuffix("s")
        .toFormatter();

int time = formatter.parsePeriod("30s").getSeconds(); //Throws IllegalArgumentException

几乎所有我传递过的字符串,都说“无效格式”。

我不明白为什么这不会工作。如果没有违法,我不能将任何内容传递给这个。有人有任何指导如何调整我的格式化设置以实现我的期望结果吗?

I am trying to convert strings like 1h 30m 5s or 5m or 38s or 1h 3s into an integer value representing total time in seconds. So for example, 1m 20s would result in an integer value of 80 for 80 seconds.

I am using Joda Time:

PeriodFormatter formatter = new PeriodFormatterBuilder()
        .appendDays().appendSuffix("d").appendSeparatorIfFieldsAfter(" ")
        .appendHours().appendSuffix("h").appendSeparatorIfFieldsAfter(" ")
        .appendMinutes().appendSuffix("m").appendSeparatorIfFieldsAfter(" ")
        .appendSeconds().appendSuffix("s")
        .toFormatter();

int time = formatter.parsePeriod("30s").getSeconds(); //Throws IllegalArgumentException

Throws an IllegalArgumentException with practically every string i pass in, saying "Invalid format".

I don't understand why this wouldn't be working. I can't pass ANYTHING into this without getting an illegalArgumentException. Does anybody have any guidance on how to tweak my formatter settings to achieve my desired result?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦里兽 2025-02-10 06:24:29

Joda Time项目现在处于维护模式。它的创建者继续领导JSR 310,它带来了Java.Time 现在内置在Java 8及以后的类。

ISO 8601标准“ nofollow noreferrer”>格式,用于时间范围代码> pnynmndtnhnmns 其中p标记起点,而t将这两个部分分开。

java.Time 类在解析/生成文本时默认使用ISO 8601标准格式。因此,无需指定格式模式。

因此,我会通过简单的文本操纵来解决您的问题。删除您的太空字符。更改为大写。

java.time.Duration.parse( "PT" + "1h 30m 5s".replace( " " , "" ).toUpperCase() )

The Joda-Time project is now in maintenance mode. It’s creator went on to lead JSR 310 which brought the java.time classes now built into Java 8 and later.

The ISO 8601 standard format for a span of time unattached to the timeline is PnYnMnDTnHnMnS where the P marks the beginning, and the T separates the two portions.

The java.time classes use the ISO 8601 standard formats by default when parsing/generating text. So no need to specify a formatting pattern.

So I would solve your problem with simple text manipulation. Delete your SPACE characters. Change to uppercase.

java.time.Duration.parse( "PT" + "1h 30m 5s".replace( " " , "" ).toUpperCase() )
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文