Skip to content

Instantly share code, notes, and snippets.

@jarrodhroberson
Created June 13, 2011 21:40
Show Gist options
  • Save jarrodhroberson/1023794 to your computer and use it in GitHub Desktop.
Save jarrodhroberson/1023794 to your computer and use it in GitHub Desktop.
Java formatted interval processing
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main
{
private static long parseInterval(final String s)
{
final Pattern p = Pattern.compile("^(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d{3})$");
final Matcher m = p.matcher(s);
if (m.matches())
{
final long hr = Long.parseLong(m.group(1)) * TimeUnit.HOURS.toMillis(1);
final long min = Long.parseLong(m.group(2)) * TimeUnit.MINUTES.toMillis(1);
final long sec = Long.parseLong(m.group(3)) * TimeUnit.SECONDS.toMillis(1);
final long ms = Long.parseLong(m.group(4));
return hr + min + sec + ms;
}
else
{
throw new IllegalArgumentException(s + " is not a supported interval format!");
}
}
private static String formatInterval(final long l)
{
final long hr = TimeUnit.MILLISECONDS.toHours(l);
final long min = TimeUnit.MILLISECONDS.toMinutes(l - TimeUnit.HOURS.toMillis(hr));
final long sec = TimeUnit.MILLISECONDS.toSeconds(l - TimeUnit.HOURS.toMillis(hr) - TimeUnit.MINUTES.toMillis(min));
final long ms = TimeUnit.MILLISECONDS.toMillis(l - TimeUnit.HOURS.toMillis(hr) - TimeUnit.MINUTES.toMillis(min) - TimeUnit.SECONDS.toMillis(sec));
return String.format("%02d:%02d:%02d.%03d", hr, min, sec, ms);
}
public static void main(final String[] args)
{
final String s1 = "36:00:00.000";
final String s2 = "23:00:00.000";
final long i1 = parseInterval(s1);
final long i2 = parseInterval(s2);
System.out.println(formatInterval(i1 - i2));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment