William Connors
William Connors

Reputation: 11

How to change the format of how a DatePicker Dialog inputs it in EditText

I have an EditText and a button, when I click on the button it opens a DatePicker and it inputs the selected date into the EditBox. Its doing that in 24hr format, which is what I want... but it only shows to 1 digit if the part of the date is 1 digit. What I want to do is apply a format so that if it is 1 digit I want it to show 2 digits. Like so. 3/2/2017, I want it to be 03/02/2017.

It is doing the same thing with Time as well. I am not sure what part of the code too post, please let me know if you require code and of what and I will post it here.

Upvotes: 0

Views: 823

Answers (2)

CSmith
CSmith

Reputation: 13458

A couple options:

Use the SimpleDateFormat class.

SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
editBox.setText(dateFormat.format(date)); 

the format string MM/dd/yyyy will provide what you need. You can also show time values if desired just by changing the format string (e.g. "MM/dd/yyyy hh:mm:ss"). This assumes you're displaying a date stored in a Date object (called date in this example).

Or use String.format,

editBox.setText(String.format("%02d/%02d/%04d",month,day,year));

the %02 means use 2 positions with leading zeros.

Upvotes: 1

OBX
OBX

Reputation: 6114

Try this :

   int year = mDatePicker.getYear();
   int month = mDatePicker.getMonth();
   int day = mDatePicker.getDayOfMonth();

    if(month < 10){

        month = "0" + month;
    }
    if(day < 10){

        day  = "0" + day ;
    }
    myText.setText(day + "-" + month + "-" + year);

Upvotes: 0

Related Questions