/** 
 * Simple Dates
 */

import java.lang.*;  // Integer
import java.io.*;   // ObjectInputStream
import java.util.zip.DataFormatException;

/**
 * @author Uwe Assmann
 * @date 2013-04-28
 * @url http://docs.oracle.com/javase/tutorial/essential/regex/index.html
 */


public class DateSimple {
    int day = 0; // initialized to 0, i.e., with a wrong postcondition
    /**
       Parse a day from a string in german date format
       Return an error code (0 for error)
    */
    public int parseDay(String d) {
	if (d.equals(""))   { System.out.println("Date string empty"); return 0; } // precondition
 	if (d.length() < 1)  { System.out.println("Date string too short"); return 0; } // invariant
	day = 0; // here, we have not matched anything
	// Matching a German date
 	if (d.matches("\\d\\d.\\d\\d.\\d\\d\\d\\d")) {
	    if (d.length() < 1)  { System.out.println("Date string too short"); return 0; } // invariant
	    // German numeric format: day.month.year
	    day = Integer.parseInt(d.substring(0,2));
	    if (day < 1 || day > 31) { // postcondition
		System.out.println("The given day must be in the range of 1..31"); 
		return 0; 
	    } 
	} else if (d.matches("\\s\\d\\d.\\s\\d\\d.\\d\\d\\d\\d")) {
	    // allowing white space character before the day
	    day = Integer.parseInt(d.substring(1,3));
	    if (day < 1 || day > 31) { // postcondition
		System.out.println("The given day must be in the range of 1..31"); 
		return 0; 
	    } 
	}
	if (d.length() < 1)  { System.out.println("Date string too short"); return 0; } // invariant
	if (day < 1 || day > 31) { System.out.println("Date format wrong"+d); return 0; } // postcondition
	return day;
    }
    // Main program. 
    public static void main(String args[]) {
	DateSimple date = new DateSimple();
	int resultDay = 0;
	resultDay = date.parseDay("04.12.2012"); 
	System.out.println("Day parsed: "+resultDay);
	resultDay = date.parseDay(" 03. 12.2012"); 
	System.out.println("Day parsed: "+resultDay);
    }
}


