Ashi
Ashi

Reputation: 207

datepicker in android - get month and day as MM -DD

I am developing an android app which uses datepicker. when i use :

request.addProperty("datetext",datePicker.getYear()+"-"+(datePicker.getMonth()+1)+"-"+datePicker.getDayOfMonth());

I am getting the output as 2013-1-7 for 7 jan 2013

But how can i get the output as 2013-01-07 for the same.

Upvotes: 1

Views: 5527

Answers (3)

Ashi
Ashi

Reputation: 207

thanks all... i got the solution...

Integer month = datePicker.getMonth()+1;
Integer day = datePicker.getDayOfMonth();
request.addProperty("datetext",datePicker.getYear()+"-"+((month.toString().length()   == 1 ? "0"+month.toString():month.toString()) )+"-"+((day.toString().length() == 1 ? "0"+day.toString():day.toString())));

so this will show months as 01 02 03 04....10 11 12 and days as 01 02 03....10 11.......

Upvotes: 4

MysticMagicϡ
MysticMagicϡ

Reputation: 28823

Date yourDate= new Date(datePicker.getYear(), (datePicker.getMonth()+1), datePicker.getDayOfMonth());

You can use SimpleDateFromat as below:

String strDate = null;
SimpleDateFormat dateFormatter = new SimpleDateFormat(
                "yyyy-MM-dd hh:mm");
strDate = dateFormatter.format(yourDate);

So you will get date in format you want (yyyy-MM-dd).

Edit:

For changing dates with change in datepicker you can try as follows:

datePicker.init(currentYear, currentMonth, currentDay, new OnDateChangedListener() {

            @Override
            public void onDateChanged(DatePicker view, int year,
                    int monthOfYear, int dayOfMonth) {
                // TODO Auto-generated method stub
                Date selectedDate = new Date(datePicker.getYear(), (datePicker
                        .getMonth() + 1), datePicker.getDayOfMonth());
                String strDate = null;
                SimpleDateFormat dateFormatter = new SimpleDateFormat(
                        "yyyy-MM-dd hh:mm");
                strDate = dateFormatter.format(selectedDate);
            }
        });

So you will find the updated date as and when date picker will change.

Upvotes: 1

Gridtestmail
Gridtestmail

Reputation: 1479

SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
java.util.Date date = null;
try 
{
date = form.parse("2013-01-7T09:39:01.607");
}
catch (ParseException e) 
{

e.printStackTrace();
}
SimpleDateFormat postFormater = new SimpleDateFormat("yyyy-MM-dd");
String newDateStr = postFormater.format(date);

Upvotes: 0

Related Questions