Search code examples
javaswingdatejcomboboxdate-format

How to put list of dates in JComboBox in 'yyyy-mm-dd' format?


I am trying to put current date and the date of the next day in a JComboBox with this code

private void dateCombo(){
    Calendar cal = new GregorianCalendar();
    int month =cal.get(Calendar.MONTH);
    int year =cal.get(Calendar.YEAR);
    int day =cal.get(Calendar.DAY_OF_MONTH);
    cmb_date.addItem(+year+"-"+(month+1)+"-"+day);
    cmb_date.addItem(+year+"-"+(month+1)+"-"+(day+1));
}

But it is showing the date in 'yyyy-m-d' format and I want it in 'yyyy-mm-dd' format.

I think i can use

Date date = new Date();
SimpleDateFormat  sdf = new SimpleDateFormat("yyyy/MM/dd");
txt_date.setText(sdf.format(date));

To get the current date in 'yyyy-mm-dd' format but what to do about the date of the next day?


Solution

  • Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, 1); //next day
    cal.getTime(); // next day's date  
    

    and you need to change format to yyyy-MM-dd for your desired format