0
votes

I have put the year, month, day on separate JComboBoxes Month JComboBox has it's own renderer to display month names instead of integer value of month. Where month begins at 0 (0-January....11-December)

So, my problem is how I can put the year, month, day together and assign it to a Date data type.

I tried concatenating year, month, day together to a String variable

int startYear = Integer.parseInt(jcmbFirstSemStartDateYear.getSelectedItem().toString() );
int startMonth = Integer.parseInt(jcmbFirstSemStartDateMonth.getSelectedItem().toString() );
int startDay = Integer.parseInt(jcmbFirstSemStartDateDay.getSelectedItem().toString() );

String startDate = startYear+"-"+startMonth+"-"+startDay; //not sure if this okay
Date completeStartDate = java.sql.Date.valueOf(startDate);
JOptionPane.showMessageDialog(null,completeStartDate);

hasConflict(completeStartDate, completeEndDate); //method to check conflict

But when I printed the value of completeStartDate, it displayed the month of February as 01.

enter image description here

I'm worried that this might be read as January instead of February when I extract the month to check for conflicts.

    public static boolean hasConflict(Date aStartDate, Date aEndDate){
        boolean hasConflict = false;
        Calendar calStart = Calendar.getInstance();
        calStart.setTime(aStartDate);
        int startYear = calStart.get(Calendar.YEAR);
        int startMonth = calStart.get(Calendar.MONTH); //extract month
        int startDay = calStart.get(Calendar.DAY_OF_MONTH);
        // ... if else conditions to compare startDate with endDate
        return hasConflict;
    }

Later on, I'll store these dates to mysql database.

Any thoughts or advice?

Thank you.

1
You could create a String representation and then parse it based on the format, or you could use LocalDate.of(year, month, dayOfMonth)MadProgrammer

1 Answers

2
votes

If possible you should probably use LocalDate.of(year, month, dayOfMonth)

LocalDate date = LocalDate.of(startYear, startMonth, startDay);

At a stretch you could create a String representation and parse it

String dateValue = startYear + "/" + startMonth + "/" + startDay;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Date data = sdf.parse(dateValue);

But given the simplicity of LocalDate, I'd go for that ... besides, if you're using Java 8 and above, you shouldn't really be using java.util.Date where you can and even if you're not, I'd consider JodaTime over java.util.Date anyway