jMonthChooser shows that it returns integer value of month, but it always return 01 as value on selecting any month

847 views Asked by At
{
    SimpleDateFormat myformat = new SimpleDateFormat("MM");             
    String abc = myformat.format(jMonthChooser2.getMonth());
}

This jMonthChooser is always returning 01.

2

There are 2 answers

0
caleb baker On

Fist thing to note is that we do not have enough code to accurately answer your question.

Second, I suggest that you add a property change listener to see if you are doing something else that could be causing this.

Use the below code to get a print out of the month that you select right after you select it.

JMonthChooser jmc = new JMonthChooser();
jmc.addPropertyChangeListener("month", new PropertyChangeListener() {
    @Override
    public void propertyChange(PropertyChangeEvent e) {
       System.out.println(e.getNewValue()));
    }
});

My best guess would be that you are running this program directly in line with your JMonthChooser and that you are always reading the default month

0
Anonymous On

java.time

    DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MM");
    String monthString = monthFormatter.format(Month.of(jMonthChooser2.getMonth() + 1));

I am adding 1 to the month number I get from the JMonthChooser to compensate since I suspect that it gives us a 0-based month number (0 through 11), whereas I know that the Month enum numbers months the same way humans do, from 1 through 12. If you find + 1 ugly (which it is), the alternative is:

    String monthString = monthFormatter.format(Month.values()[jMonthChooser2.getMonth()]);

Pick whichever you find less cryptic.

Since SimpleDateFormat is notoriously troublesome and long outdated, I am using java.time, the modern Java date and time API. It is so much nicer to work with than the old date-time classes.

Disclaimer: I don’t know JMonthChooser and have not tested my code with that class.

What went wrong in your code?

When you feed a number in the 0–11 range into SimpleDateFormat.format, the formatter understands it as a number of milliseconds since the epoch of January 1, 1970 at 00:00 UTC. So no matter which month you pick, the date-time you are trying to format, is within a few milliseconds of that date, hence the month is always January (only in some time zones it would still have been December 1969).

Links