2014-11-25 182 views
-1

我有一些输入:Java字符串日期转换成秒

1h50m22s 
2h40m10s 
33m03s 

而我必须转换成秒的Java。

已经用正则表达式'\ d + | \ D +'提取数字。

+2

如果你alerady用正则表达式提取数字,有什么问题?秒=小时* 60 * 60 +分钟* 60 +秒 – Kon 2014-11-25 00:32:06

+0

问题在哪里? – Typo 2014-11-25 00:32:27

回答

3

乔达时间

不要重新发明车轮。 Joda-Time库可以为你解析这些值。不需要正则表达式。

ISO 8601

这些值接近于标准ISO 8601格式出现。具体为Durations格式,PnYnMnDTnHnMnSP表示开始,T将日期部分与时间位置分开。如果您只有时间值,则只需将PT加上PT33m03s即可。最后转换成大写,得到PT33M03S

Joda-Time默认情况下会解析并生成此类字符串。一旦你的输入是标准格式,你可以直接将它传递给Joda-Time。跳过正则表达式。

或者,您可以指定PeriodFormatter以适合您的确切输入字符串。然后,您可以解析原始输入字符串而不转换为标准格式。

如果您对输入字符串的来源有任何控制或影响,我强烈建议修改该来源以使用ISO 8601格式。

Period

接下来,使用Period类来自动解析该值成一个周期的对象。 Period表示一个时间跨度,以月,日,小时等数字表示。 不是与宇宙历史时间表上的点相关。 (如果您在时间轴上有具体的点,使用Interval类)。

Duration

接下来,调用toStandardDuration获得Duration对象。乔达时间的持续时间代表了随着时间推移的一段时间。仅数毫秒,而不是特定的月数或小时数或这种块。

最后,在该持续时间对象调用getStandardSeconds得到您的答案。

比处理正则表达式要容易得多。由于Joda-Time已经建立,调试,磨损并且能够处理可能的输入字符串的各种排列,因此更加可靠。

示例代码

使用Joda-Time 2.5。

简洁版(不推荐)。

String input = ("PT" + "33m03s").toUpperCase(); 
long durationInSeconds = Period.parse(input).toStandardDuration().getStandardSeconds(); 

详细版本

// Convert input string to standard ISO 8601 format. 
// Alternatively, you could use a formatter to parse your original string rather than convert. 
String inputRaw = "33m03s"; 
String inputStandard = "PT" + inputRaw; // Assuming this is a time-only without date portion, prepend 'PT' to make standard ISO 8601 format. 
inputStandard = inputStandard.toUpperCase(); 

// Parse string as Period object. 
Period period = Period.parse(inputStandard); 

// Convert from Period to Duration to extract total seconds. 
Duration duration = period.toStandardDuration(); 
long durationInSeconds = duration.getStandardSeconds(); // Returns getMillis()/1000. The result is an integer division, so 2999 millis returns 2 seconds. 

转储到控制台。

System.out.println("inputRaw : " + inputRaw); 
System.out.println("inputStandard : " + inputStandard); 
System.out.println("period : " + period); // Notice how the leading zero on the 'seconds' number is gone. We have a Period *object*, not messing with strings. 
System.out.println("duration : " + duration); 
System.out.println("durationInSeconds : " + durationInSeconds); 

运行时。

inputRaw : 33m03s 
inputStandard : PT33M03S 
period : PT33M3S 
duration : PT1983S 
durationInSeconds : 1983 
0

您可能想要使用String的substring方法来提取所需的数字并将其解析为整数。例如,只需要秒就可以做:

String time = "32h45m93s"; 
String seconds = time.substring(time.indexOf('m') + 1, time.indexOf('s')); 
int seconds = Integer.parseInt(seconds); 

我没有运行它,但这是一般的想法。做同样的小时和分钟,然后

int totalSeconds = hours * 3600 + minutes * 60 + seconds; 
1

您可以轻松地做到这一点使用Joda-Time

使用模式类第一,以提取字段:

Pattern pattern = Pattern.compile("(?:(\\d+)h)?(?:(\\d+)m)?(?:(\\d+)s)?"); 
Matcher matcher = pattern.matcher("1h50m22s"); 
matcher.matches(); 
String hours = matcher.group(1); 
String minutes = matcher.group(2); 
String seconds = matcher.group(3); 

Period period = new Period(); 
if(hours != null){ 
    period = period.withHours(Integer.parseInt(hours)); 
} 
if(minutes != null){ 
    period = period.withMinutes(Integer.parseInt(minutes)); 
} 
if(seconds != null){ 
    period = period.withSeconds(Integer.parseInt(seconds)); 
} 
int totalSeconds = period.toStandardSeconds().getSeconds(); 

使用PeriodFormatterBuilder类(少解析模式灵活):

String dateText = "1h50m22s"; 
PeriodFormatterBuilder formatterBuilder = new PeriodFormatterBuilder(); 

if(dateText.contains("h")){ 
    formatterBuilder.appendHours().appendLiteral("h"); 
} 
if(dateText.contains("m")){ 
    formatterBuilder.appendMinutes().appendLiteral("m"); 
} 
if(dateText.contains("s")){ 
    formatterBuilder.appendSeconds().appendLiteral("s"); 
} 

Period period = formatterBuilder.toFormatter().parsePeriod(dateText); 
int totalSeconds = period.toStandardSeconds().getSeconds(); 
+0

很好想到Joda-Time,但是你太努力了。 Joda-Time可以直接解析持续时间字符串;不需要使用正则表达式模式类。有关详细信息和示例代码,请参阅[我的答案](http://stackoverflow.com/a/27118809/642706)。 – 2014-11-25 06:35:29

+0

其实你这样做的方式非常脆弱和难以阅读,我的代码更灵活,更易于理解。另外,我添加了一个使用PeriodFormatterBuilder类的替代方法,实现起来非常简单,但效率不高,请检查代码。 – 2014-11-25 08:17:35

+0

我不明白关于变脆的说法。我们的答案都假设没有日期部分。我们的答案都可以容忍缺少小时或分钟或秒的组件。那么脆性有什么区别? – 2014-11-25 08:22:57