Disable future dates on date picker in android

Wednesday 20 December 2017

How to convert a Date to a formatted String

I assume you would like to reverse the date format?

SimpleDateFormat can be used for parsing and formatting. 
You just need two formats, one that parses the string and the other that returns the desired print out:

SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
Date date = fmt.parse(dateString);

SimpleDateFormat fmtOut = new SimpleDateFormat("dd-MM-yyyy");
return fmtOut.format(date);
Example:

// (1) get today's date
Date today = Calendar.getInstance().getTime();

// (2) create a date "formatter" (the date format we want)
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss");

// (3) create a new String using the date format we want
String folderName = formatter.format(today);
    
// (4) this prints "Folder Name = 2009-09-06-08.23.23"

System.out.println("Folder Name = " + folderName)


SimpleDateFormat - many other custom date formats:

yyyy-MM-dd                 results in    2009-09-06
yyyyMMdd                   results in    20090906
EEE MMM dd hh:mm:ss yyyy   results in    Sun Sep 06 08:32:51 2009


SimpleDateFormat: Easily get the date, time, or datetime

// prints "Sep 6, 2009"
DateFormat dateInstance = SimpleDateFormat.getDateInstance();
System.out.println(dateInstance.format(Calendar.getInstance().getTime()));

// prints "9:03:20 PM"
DateFormat timeInstance = SimpleDateFormat.getTimeInstance();
System.out.println(timeInstance.format(Calendar.getInstance().getTime()));
  
// prints "Sep 6, 2009 9:03:20 PM"
DateFormat dateTimeInstance = SimpleDateFormat.getDateTimeInstance();
System.out.println(dateTimeInstance.format(Calendar.getInstance().getTime()));


Disable future dates on datepicker in android?


Get Current instance of Calendar in Android
Calendar c = Calendar.getInstance();


//Date Formater
SimpleDateFormat dformate = new SimpleDateFormat("dd MMM yyyy");

//calling function
private void openDatepicker() {

    int mYear = c.get(Calendar.YEAR);
    int mMonth = c.get(Calendar.MONTH);
    int mDay = c.get(Calendar.DAY_OF_MONTH);
// Launch Date Picker Dialog    
android.app.DatePickerDialog dpd = new android.app.DatePickerDialog(
getActivity(),
R.style.DialogThemeRed,
new android.app.DatePickerDialog.OnDateSetListener() {

@Override                
public void onDateSet(DatePicker view, int year,int monthOfYear, int dayOfMonth) {
                    //Set current selected date to Calendar
                    c.set(Calendar.YEAR, year);
                    c.set(Calendar.MONTH, monthOfYear);
                    c.set(Calendar.DAY_OF_MONTH, dayOfMonth);

                    //Set date to textview
                    yourTextview.setText(dformate.format(c.getTime()));
                    
                }
            }, mYear, mMonth, mDay);
    //Set Max Date for disable future dates
    dpd.getDatePicker().setMaxDate(new Date().getTime());
    dpd.show();


}