2014-11-25 177 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