Search code examples
javaandroidandroid-studiosimpledateformatdate-format

Change date format DatePickerDialog- Android studio Java


Does anyone know how to change the date format in DatePickerDialog in Android studio in Java, I need like "Mon, May 6" I need like this format instead of "M05 6, Mon"Image link .

Just a update to my code:

Calendar cal = Calendar.getInstance(Locale.ENGLISH);

crop_agetxt.setOnClickListener(v -> {
            Utils.HideKeyboard(FarmInputs.this);
            DatePickerDialog datePicker = new DatePickerDialog(FarmInputs.this, 0, new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                    sowingDate = dayOfMonth + "/" + (month + 1) + "/" + year;
                    sowingDateDb = year + "-" + (month + 1) + "-" + dayOfMonth;
                    crop_agetxt.setText(sowingDate);
                    try {
                        cropAge = GetDays(dayOfMonth + "/" + (month + 1) + "/" + year);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));

            datePicker.setCancelable(false);
            datePicker.getDatePicker().setMaxDate(System.currentTimeMillis() + Constants.days60_millisecond);
            datePicker.show();
        });

private String GetDays(String sowingdate) throws ParseException {
        Date userDob = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()).parse(sowingdate);
        Date today = new Date();
        assert userDob != null;
        long diff = today.getTime() - userDob.getTime();
        int numOfDays = (int) (diff / (1000 * 60 * 60 * 24));
        System.out.println("GetDays: " + numOfDays);
        return String.valueOf(numOfDays);
    }

Solution

  • Finally I solved the issue. Please refer the approach I have used and please let me know your toughts on this.

    Original Issue: The original issue was that the DatePickerDialog displayed dates in different formats depending on the locale settings. To ensure the DatePickerDialog consistently displays dates in the desired locale (e.g., en_US), we needed to temporarily set the locale for the dialog and then restore the original locale after the dialog is dismissed.

    Code:

    import android.content.res.Configuration;
    
    Calendar cal = Calendar.getInstance(Locale.ENGLISH);
    
    crop_agetxt.setOnClickListener(v -> {
        Utils.HideKeyboard(FarmInputs.this);
    
        // Save the current locale
        Locale currentLocale = getResources().getConfiguration().locale;
    
        // Set the desired locale
        Locale locale = new Locale("en", "US"); // Example locale (US English)
        Locale.setDefault(locale);
        Configuration config = new Configuration();
        config.locale = locale;
        getResources().updateConfiguration(config, getResources().getDisplayMetrics());
    
        DatePickerDialog datePicker = new DatePickerDialog(FarmInputs.this, 0, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                sowingDate = dayOfMonth + "/" + (month + 1) + "/" + year;
                sowingDateDb = year + "-" + (month + 1) + "-" + dayOfMonth;
                crop_agetxt.setText(sowingDate);
                try {
                    cropAge = GetDays(dayOfMonth + "/" + (month + 1) + "/" + year);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
    
                // Restore the original locale
                Locale.setDefault(currentLocale);
                Configuration config = new Configuration();
                config.locale = currentLocale;
                getResources().updateConfiguration(config, getResources().getDisplayMetrics());
            }
        }, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
    
        datePicker.setCancelable(false);
        datePicker.getDatePicker().setMaxDate(System.currentTimeMillis() + Constants.days60_millisecond);
        datePicker.show();
    
        // Restore the original locale when the dialog is dismissed
        datePicker.setOnDismissListener(dialog -> {
            Locale.setDefault(currentLocale);
            Configuration config = new Configuration();
            config.locale = currentLocale;
            getResources().updateConfiguration(config, getResources().getDisplayMetrics());
        });
    });
    

    Key Changes and Their Explanation:

    Save the Current Locale:

    Locale currentLocale = getResources().getConfiguration().locale;
    

    We save the current locale so that we can restore it after the DatePickerDialog is dismissed.

    Set the Desired Locale:

    Locale locale = new Locale("en", "US"); // Example locale (US English)
    Locale.setDefault(locale);
    Configuration config = new Configuration();
    config.locale = locale;
    getResources().updateConfiguration(config, 
    getResources().getDisplayMetrics());
    

    We set the desired locale (in this case, en_US) before showing the DatePickerDialog. This ensures that the dialog displays the date in the specified format.

    DatePickerDialog Initialization:

    DatePickerDialog datePicker = new DatePickerDialog(FarmInputs.this, R.style.calendar_theme, new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            // Date selection logic...
            // Restore the original locale
            Locale.setDefault(currentLocale);
            Configuration config = new Configuration();
            config.locale = currentLocale;
            getResources().updateConfiguration(config, getResources().getDisplayMetrics());
        }
    }, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
    

    Restore the Original Locale:

    After setting the date, we restore the original locale inside the onDateSet method and when the dialog is dismissed:

    Locale.setDefault(currentLocale);
    Configuration config = new Configuration();
    config.locale = currentLocale;
    getResources().updateConfiguration(config, getResources().getDisplayMetrics());
    

    We use an OnDismissListener to ensure the original locale is restored even if the user dismisses the dialog without selecting a date:

    datePicker.setOnDismissListener(dialog -> {
        Locale.setDefault(currentLocale);
        Configuration config = new Configuration();
        config.locale = currentLocale;
        getResources().updateConfiguration(config, getResources().getDisplayMetrics());
    });
    

    Summary This approach ensures that the DatePickerDialog displays dates in the desired locale format (en_US) and then restores the original locale after the dialog is dismissed, maintaining consistency in the date format displayed within the dialog while preserving the application's locale settings.