解析持续时间字符串 Java 7

huangapple go评论96阅读模式
英文:

Parse Duration String Java 7

问题

我想在Java 7中解析持续时间字符串,比如PT45M。我尝试过使用SimpleDateFormat,但是没有与PnDTnHnMn.nS这样的模式匹配的内容。有没有什么方法可以实现?

英文:

I want to parse Duration strings in Java 7, like PT45M. I try with SimpleDataFormat but not exist any pattern like PnDTnHnMn.nS. Is there any way to do it?

答案1

得分: 3

ThreeTen Backport

正如您可能已经了解的,以及其他答案所说,Java 8 中引入的 Duration 类可以实现这一功能。好消息是,java.time 已经被回溯到了 Java 6 和 7。从底部的链接获取回溯版本,然后开始使用。例如:

System.out.println("Java 版本:" + System.getProperty("java.version"));

Duration dur = Duration.parse("PT45M");

System.out.println("解析后的持续时间:" + dur);
System.out.println("转换为整秒:" + dur.getSeconds());

在我的计算机上,这段代码的输出是:

Java 版本:1.7.0_67
解析后的持续时间:PT45M
转换为整秒:2700

链接

英文:

ThreeTen Backport

As you may or may not be aware, and as the other answer says, the Duration class of java,time introduced in Java 8 can do that. The good news is that java.time has been backported to Java 6 and 7 too. Get the backport from the link at the bottom and go ahead. For example:

	System.out.println("Java version: " + System.getProperty("java.version"));
	
	Duration dur = Duration.parse("PT45M");
	
	System.out.println("Parsed duration: " + dur);
	System.out.println("Converted to whole seconds: " + dur.getSeconds());

On my computer output from this piece of code was:

> Java version: 1.7.0_67
> Parsed duration: PT45M
> Converted to whole seconds: 2700

答案2

得分: 0

看一下Java Duration 文档。你可以通过 parse 方法将该字符串转换为一个 Duration 对象,然后使用 getSeconds() 方法获取秒数。然后,你可以将秒数转换为常规的 Java DateTime API 对象。

英文:

Have a look at Java Documentation for Duration. You can convert that string to a duration object via parse method and get seconds with getSeconds() method. Then you can convert seconds to regular java DateTime API objects.

huangapple
  • 本文由 发表于 2020年3月4日 04:26:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/60514984.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定