How about (but it would parse an invalid date without saying anything...):
public static void main(String[] args) throws Exception {
char zero = '0';
int yearZero = zero * 1111;
int monthAndDayZero = zero * 11;
String s = "20120405";
int year = s.charAt(0) * 1000 + s.charAt(1) * 100 + s.charAt(2) * 10 + s.charAt(3) - yearZero;
int month = s.charAt(4) * 10 + s.charAt(5) - monthAndDayZero;
int day = s.charAt(6) * 10 + s.charAt(7) - monthAndDayZero;
}
Doing a quick and dirty benchmark with 100,000 iterations warm up and 10,000,000 timed iterations, I get:
- 700ms for your first method
- 350ms for your second method
- 10ms with my method.