11

I have a problem with my Datapicker

i use the code for getting date,month & year shown below

           DatePicker datePicker;
           datePicker = (DatePicker) findViewById(R.id.dateselect);

           int   day  = datePicker.getDayOfMonth();
           int   month= datePicker.getMonth() + 1;
           int   year = datePicker.getYear();

but when i print the date it shows the value 7 not 07 and for month it shows the value 2 not 02

I want these integer data in a date format ie; eg: 02-02-2013, 24-12-2013
Is there any possible way????

Rahul
  • 44,383
  • 11
  • 84
  • 103
Sibin Francis
  • 581
  • 2
  • 12
  • 30

5 Answers5

47

You can format the date like this :

int   day  = datePicker.getDayOfMonth();
int   month= datePicker.getMonth();
int   year = datePicker.getYear();
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, day);

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String formatedDate = sdf.format(calendar.getTime());

You can parse the String back to Date object by calling

Date date = sdf.parse(formatedDate);
Abhishek
  • 1,261
  • 1
  • 13
  • 30
zdesam
  • 2,936
  • 3
  • 25
  • 32
  • 1
    this is the correct way to do it. Objects to format dates already exist, there is no point in using work-arounds. – Ema Apr 17 '14 at 13:58
  • 3
    Date(year, month, day) is deprecated calendar.set(year, month, day); SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); String formatedDate = sdf.format(calendar.getTime()); – Evilripper Oct 02 '15 at 14:42
  • This answer is better than the chosen answer – Abhishek Dec 15 '17 at 08:04
27
 public String checkDigit(int number)
    {
        return number<=9?"0"+number:String.valueOf(number);
    }

basic use:

month=checkDigit(month);
input 7
output 07
   String date=checkDigit(monthOfYear+1)+"/"+checkDigit(dayOfMonth)+"/"+year;
Pragnani
  • 20,075
  • 6
  • 49
  • 74
3
<?xml version="1.0" encoding="utf-8"?>

<Button
    android:id="@+id/btnChangeDate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Change Date" />

<TextView
    android:id="@+id/lblDate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Current Date (M-D-YYYY): "
    android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
    android:id="@+id/tvDate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text=""
    android:textAppearance="?android:attr/textAppearanceLarge" />

<DatePicker
    android:id="@+id/dpResult"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

package com.mkyong.android;

   import java.util.Calendar;
 import android.app.Activity;
 import android.app.DatePickerDialog;
 import android.app.Dialog;
 import android.os.Bundle;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.widget.Button;
 import android.widget.DatePicker;
 impot android.widget.TextView;

 public class MyAndroidAppActivity extends Activity {

private TextView tvDisplayDate;
private DatePicker dpResult;
private Button btnChangeDate;

private int year;
private int month;
private int day;

static final int DATE_DIALOG_ID = 999;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    setCurrentDateOnView();
    addListenerOnButton();

}

// display current date
public void setCurrentDateOnView() {

    tvDisplayDate = (TextView) findViewById(R.id.tvDate);
    dpResult = (DatePicker) findViewById(R.id.dpResult);

    final Calendar c = Calendar.getInstance();
    year = c.get(Calendar.YEAR);
    month = c.get(Calendar.MONTH);
    day = c.get(Calendar.DAY_OF_MONTH);

    // set current date into textview
    tvDisplayDate.setText(new StringBuilder()
        // Month is 0 based, just add 1
        .append(month + 1).append("-").append(day).append("-")
        .append(year).append(" "));

    // set current date into datepicker
    dpResult.init(year, month, day, null);

}

public void addListenerOnButton() {

    btnChangeDate = (Button) findViewById(R.id.btnChangeDate);

    btnChangeDate.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            showDialog(DATE_DIALOG_ID);

        }

    });

}

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DATE_DIALOG_ID:
       // set date picker as current date
       return new DatePickerDialog(this, datePickerListener, 
                     year, month,day);
    }
    return null;
}

private DatePickerDialog.OnDateSetListener datePickerListener 
            = new DatePickerDialog.OnDateSetListener() {

    // when dialog box is closed, below method will be called.
    public void onDateSet(DatePicker view, int selectedYear,
            int selectedMonth, int selectedDay) {
        year = selectedYear;
        month = selectedMonth;
        day = selectedDay;

        // set selected date into textview
        tvDisplayDate.setText(new StringBuilder().append(month + 1)
           .append("-").append(day).append("-").append(year)
           .append(" "));

        // set selected date into datepicker also
        dpResult.init(year, month, day, null);

    }
};

}

Rohit
  • 3,401
  • 4
  • 33
  • 60
2

Starting from API level 12, DatePicker has public CalendarView getCalendarView (), using this view you can get the date:

long dateTime = datePicker.getCalendarView().getDate();
Date date = new Date(dateTime);

Then format if needed:

DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
String formattedDate = dateFormat.format(date);
negersiu
  • 552
  • 3
  • 20
  • https://developer.android.com/reference/android/widget/DatePicker#getCalendarView() This method was deprecated in API level 24. Not supported by Material-style calendar mode – LM.Croisez Sep 30 '19 at 14:36
1

You can use a custom method for setting date and month in the desired format

    private static String  pad(int c)
    {
        return c>=10 ? ""+c : "0"+c;      
    }

Instead of using the values for date and month use pad(date) and pad(month)

Hope this helps.

Aswathy P Krishnan
  • 11,728
  • 7
  • 27
  • 45