Created
April 1, 2017 18:31
-
-
Save vkdinventor/93a112366a68f7eb6135e57f287687e5 to your computer and use it in GitHub Desktop.
Converting Youtube Data API V3 video duration (e.g. PT1H9M24S ) to hh:mm:ss format in java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.vkdinventor.code; | |
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
/** | |
* Created by vikash on 01-04-2017. | |
*/ | |
public class TimeConverter { | |
public static void main(String[ ] args){ | |
String [] s = new String[]{"PT1H9M24S","PT1H1S","PT2H1S","PT23H2M","PT23M2S","PT31S","PT"}; | |
for (String input:s){ | |
System.out.println(new TimeConverter().converttoHHMMSS(input)); | |
} | |
} | |
public String converttoHHMMSS(String youtubetime) { | |
String pattern = new String("^PT(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+))S?$"); | |
Pattern r = Pattern.compile(pattern); | |
String result; | |
Matcher m = r.matcher(youtubetime); | |
if (m.find()) { | |
String hh = m.group(1); | |
String mm = m.group(2); | |
String ss = m.group(3); | |
mm = mm !=null?mm:"0"; | |
ss = ss !=null?ss:"0"; | |
result = String.format("%02d:%02d", Integer.parseInt(mm), Integer.parseInt(ss)); | |
if (hh != null) { | |
result = hh + ":" + result; | |
} | |
} else { | |
result = "00:00"; | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment