Search code examples
javacalendar

Java Checking number months


I think I figure out what question I am trying to ask I dont want get(Calendar.MONTH) I want the month not to be greater than the last caldendar month that is why i am doing month -1, i realize that if i use get(calendar.MONTH) it is getting month of november I just want to see check and make sure its not a greater then the december to us 12 to the computer 11. that is why every other month is invalid that is the question I am trying to get an answer for!?

public Date(String inString)  
{
    int month;// is define by cutting up the inString like this
    int day; // same as month
    int getSlash;

    getSlash = inStr.indexOf('/');
    month = Integer.parseInt(inStr.substring(0,getSlash));
    day = Integer.parseInt(inStr.substring(getSlash + 1));

    inStr = String.format("%02d/%02d%n",month,day);// padformatting string
    inStr=  new SimpleDateFormat("MM/dd").format(new SimpleDateFormat("MM/dd").parse(inStr));// checking to see if a actualdate

    GregorianCalendar cal = new GregorianCalendar();

    // this is what I don't understand after reading

    if (month -1 > cal.get(Calendar.MONTH ) // how do I get it to say int of the month if the user types in 12 it gets invalid
    {
        System.out.Println("Invalid Month -> " + month");
    }

}

when I do this all but month 11 is considered not vailid any one know why? I can not figure it out.


Solution

  • Judging by these related questions, I think you have a number of problems before that.

    You're trying to code something that is already coded using existing libraries. This redundant code is causing conflicts.

    You may

    A) Use an existing library.

    B) Code the solution yourself to learn.

    If you go for A you just need.

    public Date toDate( String inStr ) {
        return new SimpleDateFormat("MM/dd").parse(inStr);
    }
    

    And that's it!

    If you go for B, what you need to to is first create an algorithm ( in a paper sheet ) and describe what steps do you need to solve the problem.

    like

    • Take the string
    • Split it in part by "/"
    • Convert them to numbers
    • Validate if the first number is between 1 and 31
    • Validate the month ( is in 1 and 12 )
    • If month is 2 then the day must be < 29

    etc etc et

    Once you have all those steps clearly defined, you may the proceed to the codification. Some of them will translate seamlessly and some other will need more work. For some steps you may create code that is not as good as it could be but it works and for other parts you just won't have a clue.

    But if you don't have an algorithm, you'll be hitting walls over and over. And getting problems as the one you're describing.

    First make it run in the paper in your own words, later find out how to code it.

    Here's a related entry: Process to pass from problem to code: How did you learn?