Created
August 16, 2012 18:44
-
-
Save hamaluik/3372567 to your computer and use it in GitHub Desktop.
Parsing XwXdXhXmXs time into number of seconds
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
private boolean isLong(String str) { | |
try { | |
Long.parseLong(str); | |
} | |
catch(NumberFormatException e) { | |
return false; | |
} | |
return true; | |
} | |
public long parseTime(String time) { | |
long secondsTime = -1; | |
try { | |
long weeks = 0; | |
long days = 0; | |
long hours = 0; | |
long mins = 0; | |
long secs = 0; | |
String nums = ""; | |
for(int j = 0; j < time.length(); j++) { | |
String c = time.substring(j, j+1); | |
if(isLong(c)) { | |
nums += c; | |
continue; | |
} | |
long num = Long.parseLong(nums); | |
if(c.equals("w")) weeks = num; | |
else if(c.equals("d")) days = num; | |
else if(c.equals("h")) hours = num; | |
else if(c.equals("m")) mins = num; | |
else if(c.equals("s")) secs = num; | |
else throw new IllegalArgumentException("invalid time measurement: " + c); | |
nums = ""; | |
} | |
// now get the total time | |
secondsTime = secs + (mins * 60) + (hours * 3600) + (days * 86400) + (weeks * 604800); | |
} | |
catch(Exception e) { | |
error(e.getMessage()); | |
} | |
return secondsTime; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment