1

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);
}
Community
  • 1
  • 1
Banana
  • 2,435
  • 7
  • 34
  • 60

1 Answers1

1

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());
slymnozdmrc
  • 390
  • 2
  • 8
  • 20
  • TX for the fast reply. I found this and I wanted to use it: mCalendar = Calendar.getInstance(); String month = mCalendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault()); but I am a beginner coder and am not sure how to use it with the stringBuilder which I used to display the date and the time. – Banana Mar 03 '16 at 12:24
  • 1
    @Kemo i hope this one help you. – slymnozdmrc Mar 03 '16 at 12:32
  • I don't have the time to check this now, but i will try this tomorrow or the day after and mark your answer accepted if it helped :) Thanks again for the fast answer :) – Banana Mar 03 '16 at 12:43
  • 1
    @Kemo try it if you take any error or something wrong just write the comment i m glad try to help you :) – slymnozdmrc Mar 03 '16 at 13:08
  • Hey Slymn, what I wanted here is to display the date and time after the user selected it from the datetimepicker. I wanted to display it in the TextViews. So far the examples used the stringBuilder and append. I tried changing my updateDate to this: private void updateDate() { Date date = new Date(mYear - 1900, mMonth, mDay); mDateDisplay = DateFormat.format("yyyy.MM.dd", date).toString(); but I got incompatyble types error: required android.widget.TextView, found java.lang.String Sorry for bothering you and thanks in advance :) – Banana Mar 07 '16 at 08:34
  • 1
    @Kemo hi what is mDateDisplay ? is it your textbox? if this is your textbox youshould use mDateDisplay.SetText(DateFormat.format("yyyy.MM.dd", date).toString()); And please make sure with debuging the value of DateFormat.format("yyyy.MM.dd", date).toString() return correct value. Also you can see this value with using Log. – slymnozdmrc Mar 07 '16 at 11:14
  • 1
    @Kemo actually this second answer should help your question. This Timezone issue. TimeZone toTimeZone = TimeZone.getTimeZone("CST"); they solve the problem with this. "CST" means that Central Time Zone find the USA or EU time zone with this method. than follow the link aswer than your problem may solve. http://stackoverflow.com/questions/9429357/date-and-time-conversion-to-some-other-timezone-in-java – slymnozdmrc Mar 07 '16 at 11:31
  • I tried to display selected date like this: `long date = System.currentTimeMillis(); SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy"); String dateString = sdf.format(date); mDateDisplay.setText(dateString);` but it shows only current time and date, not the one I selected from the picker. How can I display the selected date here? – Banana Mar 07 '16 at 11:49
  • @Kemo Selected date means that user selection on datepicker right ? if is it you should do this on datepicker set item listener in this tutorial. http://www.tutorialspoint.com/android/android_datepicker_control.htm after select the date than apply my solution :) – slymnozdmrc Mar 07 '16 at 12:06
  • That is right - This is the problem `long date = System.currentTimeMillis();` because it shows the current time. I tried to replace it with this: ` c.set(mYear, mMonth, mDay); String date = new SimpleDateFormat("MMM dd, yyyy").format(c.getTime()); mDateDisplay.setText(date);` – Banana Mar 07 '16 at 12:11
  • 1
    Please don use System.currentTimeMillis(); this not user selection this is system time. You have to take user selection from datepicker. private DatePickerDialog.OnDateSetListener myDateListener = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) { // arg1 = year // arg2 = month // arg3 = day } }; like this from http://www.tutorialspoint.com/android/android_datepicker_control.htm – slymnozdmrc Mar 07 '16 at 12:14
  • I finished it, I know we shouldn't use chat to say thank you, but I really want to say thanks for your patience and for sharing your knowledge. I am learning how to code by myself so any help is really appreciated, so thanks again for everything :) **_I added the code I used in the edit section of my question._** – Banana Mar 07 '16 at 12:32
  • 1
    @Kemo Im happy to hear that also you solve your problem this is good. You're welcome :) When you have a problem about code, first of all follow the instruction in http://developer.android.com. this give you to control your code and has best solution. Do it your own solution always :) Have a good day – slymnozdmrc Mar 07 '16 at 12:38