我的时间格式有问题。有时我的值是 hh:mm:ss 格式,有时是 mm:ss 格式。
我的代码如下:
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String time = "01:48:00"
Date remainedTimeDate = sdf.parse(time);
它起作用了,当我得到格式 hh:mm:ss 但当我有时间使用格式 mm:ss 时,我得到一个错误,比如无法解析值。是否可以动态更改日期格式?
最佳答案
java.time.Duration
假设您的字符串表示时间量(例如,持续时间),在 Java 中用于它的正确类是 java.time 中的 Duration
,现代 Java 日期和时间 API .不幸的是,Duration
无法开箱即用地解析您的字符串。它有一个只接受 ISO 8601 格式的 parse
方法。一段时间内的 ISO 8601 格式类似于 PT1H48M30S
。一开始它看起来很不寻常,但当您知道如何操作时,它就很容易阅读。将刚刚给出的示例阅读为 1 小时 48 分 30 秒的时间段。因此,为了解析 hh:mm:ss 和 mm:ss 格式的字符串,我首先使用几个正则表达式将它们转换为 ISO 8601。
// Strings can be hh:mm:ss or just mm:ss
String[] examples = { "01:48:30", "26:57" };
for (String example : examples) {
// First try to replace form with two colons, then form with one colon.
// Exactly one of them should succeed.
String isoString = example.replaceFirst("^(\\d+):(\\d+):(\\d+)$", "PT$1H$2M$3S")
.replaceFirst("^(\\d+):(\\d+)$", "PT$1M$2S");
Duration dur = Duration.parse(isoString);
System.out.format("%8s -> %-10s -> %7d milliseconds%n", example, dur, dur.toMillis());
}
此外,我的代码还展示了如何将每个持续时间转换为毫秒。输出是:
01:48:30 -> PT1H48M30S -> 6510000 milliseconds 26:57 -> PT26M57S -> 1617000 milliseconds
链接
- Oracle tutorial: Date Time解释如何使用 java.time。
- Wikipedia article: ISO 8601
关于java - 如何动态更改日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67211960/