Last change 14/07/2010
a little piece of code that can convert human input into a timespan (milliseconds)
The code
I already used this snipped quite a few times, since it is pretty versatile
public class TimespanUtil {
/**
* converts a human entered timespan into a long (millisecondS).
* Possible formats are:
* * y: years
* * M: months
* * w: week
* * d|t: day
* * h: hour
* * m: minute
* * s: second
* for time only you can also use:
* 5:10 (5m10s)
* 10.5 (10.5s)
* other examples:
* 5.h3.5d
* 3.5d - 5h2m + 1s
* @param s the timespan
* @return the timespan
*/
public static long getTimespan(String s) {
long totalSpan = 0;
// check what kind of parsing we have: time only or with chars
String w = s.replaceAll("[^yMmhdtsw:.0-9]", "");
StringBuilder sb = new StringBuilder();
boolean haveNum = false;
for(int i =0; i < w.length(); i++) {
char c = w.charAt(i);
// numbers are just appended
if (c == ',')
c = '.';
if ((c >= '0' && c <= '9') || c == '.')
{
sb.append(c);
haveNum=true;
continue;
}
else
{
if (haveNum)
{
totalSpan += millis(Double.parseDouble(sb.toString()), c);
sb = new StringBuilder();
}
}
}
if(sb.length() > 0)
totalSpan += millis(Double.parseDouble(sb.toString()), ' ');
return totalSpan;
}
public static double millis (double d, char c) {
switch(c)
{
case 'y':
return d * 365 * 24 * 3600000l;
case 'M':
return d * 30 * 24 * 3600000l;
case 'm':
case ':':
return d * 60000l;
case 'h':
return d * 3600000l;
case 'd':
case 't':
return d * 24 * 3600000l;
case 'w':
return d * 7 * 24 * 3600000l;
default:
return d * 1000;
}
}
}