Got youtube video time, via Json PT24M30S, how can I translate, is it a time in seconds?
- oneMultiply minutes by 60 and add seconds? - iksuy
- Well, I understood it, how can I get the numbers from the PT1H24M30S? - Enjo Flash
- If the question "how do I pull the numbers from the PT1H24M30S", then I need to ask in "how do I pull the numbers from the PT1H24M30S" and not "how to translate in seconds." - Enikeyschik
- What is the relation to android? - Enikeyschik
- It is possible through regular expressions, several times through String.substring. and many more options. - Dred
|
1 answer
There are lots of options. For example, you can parse the line with your hands, it's easier backwards, you get three fields, for hours, minutes, seconds, you see the corresponding character in the line, it means numbers in front of them, read them, get a number, write down, like this:
static int timeStringtoSeconds(String time) { int h = 0; int m = 0; int s = 0; char currentModifier = 'S'; String currentValue = ""; for (int i = time.length() - 1; i >= 0; i--) { if (Character.isAlphabetic(time.charAt(i))) { if (!currentValue.isEmpty()) { switch (currentModifier) { case 'S': s = Integer.parseInt(currentValue); break; case 'M': m = Integer.parseInt(currentValue); break; case 'H': h = Integer.parseInt(currentValue); break; } currentValue = ""; } currentModifier = time.charAt(i); } else { currentValue = time.charAt(i) + currentValue; } } return h * 60 * 60 + m * 60 + s; }
Or it can be divided into groups approximately regularly, and then simply to compose a value from the groups, something like this:
static int regex(String time){ Pattern p = Pattern.compile("PT(\\d*H)?(\\d*M)?(\\d*S)?"); Matcher m = p.matcher(time); int result = 0; if(m.find()){ String hg = m.group(1); String mg = m.group(2); String sg = m.group(3); result += hg != null ? Integer.parseInt(hg.substring(0, hg.length() - 1)) * 60 * 60 : 0; result += mg != null ? Integer.parseInt(mg.substring(0, mg.length() - 1)) * 60 : 0; result += sg != null ? Integer.parseInt(sg.substring(0, sg.length() - 1)) : 0; } return result; }
|