Search code examples
javaandroiddatetimelocale

Displaying local format in a custom dateTime picker in android


I am beginner coder, currently making a reminder app. So far this app does the following:

  • When you click the datetime picker it opens my custom datetime picker
  • You select the date and the time (that is at least 10 minutes from now and is in the next 30 days)
  • Date and time you selected displays in TextView field on screen

Since there is no datetime picker I made a custom one. I tried a number of approaches and this is the only one that worked for me. So now I have this problem - I want to display the date and the time format that is the same as the format on the phone - for USA it would be month/day/year and AM/PM, for Europe day/month/year and 24hr format. If there is no way to do this I would like to at least display the month name - like this 03 Mar. I used StringBuilder to append day, month and year. This can be confusing if the date is for example 02/03/2016. As for the time I am displaying 24 hour format with added "0" for one digit numbers.

As I said I am a beginner so I am having problems using examples like this with StringBuilder. I also tried this example instead of StringBuilder, but I got but I got incompatyble types error: required android.widget.TextView, found java.lang.String.

My current way of displaying the date and time is shown bellow in the "// Update date and time" section. The rest of the code is here for for reference for anyone who needs to create a custom datetime picker :)

private Button mPickDate;
private TextView mDateDisplay;
private TextView mTimeDisplay;

final Calendar c = Calendar.getInstance();
private int mYear = c.get(Calendar.YEAR);
private int mMonth = c.get(Calendar.MONTH);
private int mDay = c.get(Calendar.DAY_OF_MONTH);
private int mHour = c.get(Calendar.HOUR_OF_DAY);
private int mMinute = c.get(Calendar.MINUTE);

static final int TIME_DIALOG_ID = 1;
static final int DATE_DIALOG_ID = 0;

And the rest of the code:

//Update date and time
private void updateDate() {
    mDateDisplay.setText(
            new StringBuilder()
                    .append(mDay).append("/")
                    .append(mMonth + 1).append("/")
                    .append(mYear).append(" "));
    showDialog(TIME_DIALOG_ID);
}

public void updateTime() {
    mTimeDisplay.setText(
            new StringBuilder()
                    .append(pad(mHour)).append(":")
                    .append(pad(mMinute)));
}

// Append 0 if number < 10
private static String pad(int c) {
    if (c >= 10)
        return String.valueOf(c);
    else
        return "0" + String.valueOf(c);
}

// Generate DatePickerDialog and TimePickerDialog
private DatePickerDialog.OnDateSetListener mDateSetListener =
        new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year,
                                  int monthOfYear, int dayOfMonth) {
                mYear = year;
                mMonth = monthOfYear;
                mDay = dayOfMonth;
                updateDate();
            }
        };

private TimePickerDialog.OnTimeSetListener mTimeSetListener =
        new TimePickerDialog.OnTimeSetListener() {
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                mHour = hourOfDay;
                mMinute = minute;

                Calendar c2 = Calendar.getInstance();

                if (mYear == c2.get(Calendar.YEAR)
                        && mMonth == c2.get(Calendar.MONTH)
                        && mDay == c2.get(Calendar.DAY_OF_MONTH)
                        && (mHour < c2.get(Calendar.HOUR_OF_DAY) || (mHour == c2.get(Calendar.HOUR_OF_DAY) && mMinute <= (c2.get(Calendar.MINUTE) + 10))
                )
                        ) {

                    Toast.makeText(SetDateTimeActivity.this, "Set time at least 10 minutes from now", Toast.LENGTH_LONG).show();
                } else {
                    updateTime();
                }

            }
        };

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
        case DATE_DIALOG_ID:
            DatePickerDialog datePickerDialog = new DatePickerDialog(this,
                    mDateSetListener,
                    mYear, mMonth, mDay);
            c.add(Calendar.MONTH, +1);
            long oneMonthAhead = c.getTimeInMillis();
            datePickerDialog.getDatePicker().setMaxDate(oneMonthAhead);
            datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
            return datePickerDialog;

        case TIME_DIALOG_ID:
            TimePickerDialog timePickerDialog =
                    new TimePickerDialog(this,
                            mTimeSetListener, mHour, mMinute, false);

            return timePickerDialog;
    }
    return null;
}

Thank you in advance :)

EDIT - the solution I used in my code:

// Update date and time
private void updateDate() {
    c.set(mYear, mMonth, mDay);
    String date = new SimpleDateFormat("MMM dd, yyyy").format(c.getTime());
    mDateDisplay.setText(date);

    showDialog(TIME_DIALOG_ID);
}

public void updateTime() {
    c.set(mYear, mMonth, mDay, mHour, mMinute); // check why do I need to add year,month,day
    String time = new SimpleDateFormat(" hh:mm a").format(c.getTime());
    mTimeDisplay.setText(time);
}

Solution

  • You can change the format whatever you want example is in below.

    String strCurrentDate = "Wed, 18 Apr 2012 07:55:29 +0000";
    SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss Z");
    Date newDate = format.parse(strCurrentDate);
    
    format = new SimpleDateFormat("MMM dd,yyyy hh:mm a");
    String date = format.format(newDate);
    

    Or your local format

    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy HH:mm", Locale.getDefault());
    String formatted = sdf .format(900000);
    System.out.println(simpleDateFormat.parse(formatted));
    

    or you can take year month day from calander and format it.

       Calendar cal = Calendar.getInstance();
        cal.get(Calendar.YEAR);
        cal.get(Calendar.DAY_OF_MONTH);
        cal.get(Calendar.MONTH);
        String format = new SimpleDateFormat("E, MMM d, yyyy").format(cal.getTime());
    

    you just change the format for whatever your format search usa date format an put it in

    SimpleDateFormat("here").format(cal.getTime());