Skip to content

Instantly share code, notes, and snippets.

@hamaluik
Created August 16, 2012 18:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hamaluik/3372567 to your computer and use it in GitHub Desktop.
Save hamaluik/3372567 to your computer and use it in GitHub Desktop.
Parsing XwXdXhXmXs time into number of seconds
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