Reputation: 119
While setting a value in an EditText
from a DatePicker
, how do i set it as for ex 25-03-2014 instead of 25-3-2014.
Cos it displays 25-3-2014 with the missing '0' before the month(mm) everytime.
Thanks.
Upvotes: 1
Views: 1351
Reputation: 1564
Use Below given code can solve you problem...
DatePicker dp = (DatePicker)dialog.findViewById(R.id.datePicker1);
dp.getDayOfMonth();
dp.getMonth();
dp.getYear();
if(dp.getMonth()+1<10)
editText.setText(dp.getDayOfMonth()+"-"+"0"+(dp.getMonth() + 1 )+"-"+dp.getYear());
if(dp.getDayOfMonth()<10)
editText.setText("0"+dp.getDayOfMonth()+"-"+(dp.getMonth() + 1 )+"-"+dp.getYear() );
if(dp.getMonth()+1<10 && dp.getDayOfMonth()<10)
editText.setText("0"+dp.getDayOfMonth()+"-"+"0"+(dp.getMonth() + 1 )+"-"+dp.getYear() );
if(dp.getMonth()+1>9 && dp.getDayOfMonth()>9)
editText.setText( dp.getDayOfMonth()+"-"+(dp.getMonth() + 1 )+"-"+dp.getYear());
dialog.dismiss();
Upvotes: 0
Reputation: 6142
Simply make it like this,
final String DATE_FORMAT = "dd-MM-yyyy";
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
Upvotes: 0
Reputation: 10877
YourEditText = (EditText) findViewById(R.id.your_edittext);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String date = sdf.format(new Date(System.currentTimeMillis()));
if (date.contains("/")) {
date = date.replace("/", "-");
}
YourEditText.setText(date);
Add Click Event on YourEditText inside xml :
android:onClick="onTime"
Code Snippet:
Please extend your Activity
from FragmentActivity
public void onTime(View v) {
DialogFragment newFragment = new FromDatePickerFragment();
newFragment.show(getSupportFragmentManager(), "From Date");
}
class FromDatePickerFragment extends DialogFragment implements
OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int yr = c.get(Calendar.YEAR);
int mnth = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of TimePickerDialog and return it
return new DatePickerDialog(getActivity(), this, yr, mnth, day);
}
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
String date;
monthOfYear++;
if (dayOfMonth < 10) {
date = "0" + dayOfMonth + "-";
} else {
date = dayOfMonth + "-";
}
if (monthOfYear < 10) {
date += "0" + monthOfYear + "-";
} else {
date += monthOfYear + "-";
}
date += year;
YourEditText.setText(date);
}
}
Upvotes: 1
Reputation: 1933
You can use SimpleDateFormat
class as "dd/MM/yyyy".
check the documentation.
http://developer.android.com/reference/java/text/SimpleDateFormat.html
Upvotes: 0