views:

299

answers:

5

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.

+3  A: 

I'm guessing what you want is

cal.get(Calendar.MONTH)

which will return you zero-based index of month within year.

Your question is very unclear, however, and your parsing code seems a bit more involved than it has to be. Perhaps if you'd explained better what you're trying to do, someone would be able to suggest a better approach.

ChssPly76
That is accurate but when I use this one I get all my other months invalid
daddycardona
+4  A: 

Parsing dates and times yourself is a bad idea - as is using Java's built-in functionality.

I can't tell exactly what you want to do or what's wrong, but I think it's safe to say that using Joda Time would be a good idea.

Then instead of using get with mystical constants - and adjusting for months being 0-based - you can just use ReadableDateTime.getMonthOfYear() or some other pleasantly-named method. Much nicer.

For instance, to get the current month, you'd use:

int currentMonth = new DateTime().getMonthOfYear();

That uses the ISO calendar system and the current default time zone. Personally I'm not too fond of defaulting the time zone, so you may want:

int currentMonth = new DateTime(DateTimeZone.UTC).getMonthOfYear();

I suspect the ISO calendar system will be fine for you though :)

(As ChssPly76 says, cal.get(Calendar.MONTH) will get you the 0-based month number with your current code, but that's a horrible API in my opinion.)

EDIT: Now you've updated your question, you should diagnose the problem by breaking it down a bit more. Is this a problem in terms of the user input, or comparing with the current month? If it's the "comparing with the current month" bit that's the problem, that's easy to show in a short but complete program which doesn't have all the rest of the stuff around it:

import java.util.*;

public class Test
{
    public static void main(String[] args)
    {
        // It's currently November
        int userInput = 11;

        Calendar cal = Calendar.getInstance();
        int currentMonth = cal.get(Calendar.MONTH) + 1;

        if (userInput == currentMonth)
        {
            System.out.println("Yes, that's the current month");
        }
        else
        {
            System.out.println("No, the current month is " + currentMonth);
        }
    }
}

I've compensated for java.util.Calendar using 0 months by adding one to the value returned rather than subtracting one from the user input, but it's the same basic premise.

Now, if it's getting the user input which is the problem, you don't need to bother with the current month - just check whether you're getting what you expect.

A lot of programming is basically dividing a problem into two pieces. Here you have two issues:

  • Parsing user input
  • Comparing with the current month

Work out which one is the problem, and edit your question to address just that aspect.

Jon Skeet
Apache commons lang can also be used for some tasks. Looking at apache commons is often a good idea before implementing something:)
extraneon
@extraneon: When it comes to date and time APIs, I don't look any further than Joda Time. I seem to recall looking at the apache commons date and time libraries a while ago and not being too impressed.
Jon Skeet
I am a big rookie at this and need it for college so thanks everyone for the help I wish i could make my questions easier for all to understand.
daddycardona
I think I figure out what question I am trying to ask I dont want getMONTH I want the month to be 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
daddycardona
@daddycardona: I'm afraid I really still don't understand what you're trying to achieve. I think the problem here isn't about computing - it's about communication. Slow yourself down, and write in full sentences with appropriate punctuation and capitalization. Read your text afterwards, and consider whether you'd understand it, with no other background information.
Jon Skeet
A: 
int month;// is define by cutting up the inString like this
int day; // same as month
int getSlash;
getSlash = inString.indexOf('/');
month = Integer.parseInt(inString.substring(0,getSlash));
day = Integer.parseInt(inString.substring(getSlash + 1));
inStr =String.format("%02d/%02d%n",month,day);// padformatting string

Impressive. Why are you trying to convert from "MM/dd" to "MM/dd"?

BalusC
@ BalusC. Only because the teacher wants me to do so lol
daddycardona
In the future, please add `homework` tag to your school-related questions so that nobody will going to suggest you solutions which are *far* beyond your scope, such as JodaTime and so on.
BalusC
Lolling around isn't going to encourage us to take you seriously btw.
BalusC
good to go I did not know they had that tag
daddycardona
+2  A: 

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?

OscarRyz
Oscar you answer all my questions your awesome and thanks man. I also did have that but just not as good as yours lol
daddycardona
:) You know you can always click on that tick to mark the answer as accpeted ;) ( if it does solve your question of course )
OscarRyz
A: 

I agree with the other answers; use SimpleDateFormat to parse, if the assignment allows you to.

You can also use the Calendar class to do something like this by switching lenient interpretation of values off, then setting the fields, and then forcing the Calendar instance to recompute it's internal counters. This will throw an exception if the field values are inconsistent. Like so:

import java.util.*;

public class Test {
    public static void main(String[] args) {
        Calendar c1=new GregorianCalendar();
        c1.setLenient(false);
        c1.set(2010,1,23);        // should work: Jan. 23, 2010
        c1.getTimeInMillis();     // will revalidate the calendar fields
        System.out.println("OK: "+c1.toString());
        try {
            c1.set(2010,2,35);     // invalid date: Feb. 35, 2010
            c1.getTimeInMillis();  // revalidate... should throw exception!
            System.out.println("OK: "+c1.toString()); // never happens
        } catch(IllegalArgumentException t) {
            System.out.println("FAIL: "+c1.toString());
            t.printStackTrace();
        }
    }
}

Here the calls to getTimeInMillis() force Calendar to revalidate its internal fields; the call will throw IllegalArgumentException if the values are inconsistent with normal Calendar time (i.e. out of range). If you'd left the default of lenient=true enabled, the second call would succeed, but you'd end up with a day in March as Calendar tries to figure out what you meant!

The only real catch is that to do a computation like this properly, you must know what the year is so that Calendar can do leap year calculations for you to get the number of days in February correct.

If for some reason you really don't care about the year, you could just hardcode a year that you know isn't a leap year... like 2009. Be sure to document that you're doing something weird like that though! It's a bit of a hack, and that's often an indication that you're doing something in a less than optimal way!

But, as mentioned in the other answers, either SimpleDateFormat, or a little array-based lookup table is probably the easy and clean answer here.

Hope you find this educational.

Sarah K