Search code examples
androidandroid-datepicker

DateTime incorrect month and how convert to dd/mm/yyyy in database


I want to let the user choose a Date from a DatePicker and store it into database, and then convert it to dd/mm/yyyy format.

        dp =(DatePicker)findViewById(R.id.DateActivity);
        setDate.setOnClickListener(new OnClickListener() 
        {
        @Override
        public void onClick(View v) {
            requestDate.setText("Day" + dp.getDayOfMonth() + " Month " + (dp.getMonth() + 1)+ " Year " + dp.getYear());
        }
    });

The output is Day 9 Month 2 Year 2014. The output months is less by one for every month I choose so I add 1 to the month. Why this is the case? But the main problem is how do I convert it to 09022014 and store it in the database? If the db has the format dd/mm/yyyy does it means it will not accept my output?


Solution

  • java.util.Calendar treats the months as a zero-based list, so the DatePicker follows this convention as well (see the documentation for DatePicker.init). It's confusing, but that's just the way Java does it (for now, at least). Adding 1 like you're doing will work just fine.

    As for converting the date, you can use the SimpleDateFormat class to format the date however you like. For what you said, the format pattern string would be "ddMMyyyy". See the sample code below:

    // Build Calendar object from DatePicker fields.
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.MONTH, myDatePicker.getMonth());
    cal.set(Calendar.DAY_OF_MONTH, myDatePicker.getDayOfMonth());
    cal.set(Calendar.YEAR, myDatePicker.getYear());
    
    // Convert date to desired format.
    SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");
    String dateString = sdf.format(cal.getTime());
    int dateInt = Integer.parseInt(dateString); // if you want it as an int instead
    

    You may want to consider storing the date as 20140209 ("yyyyMMdd", year-month-day) instead for sorting purposes, as that will naturally allow it to be sorted chronologically.