Display date in proper format in Java

Date format is set by two steps.
1. Use SimpleDateFormat() to set the date mask.
2. Use format(Date d) or parse(String text) to convert it;
Please note that format(Date d) use Date type as parameter.


Date to string
    Date dateVal=new Date(); //the date and time value right now
    SimpleDateFormat formatDate = new SimpleDateFormat("MM/dd/yyyy");
    String = formatDate.format(dateVal);


String to Date
    SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
    String dateStringToParse = "09/02/2001";	//09/02/2001 and 9/2/2001 will have same result
    Date date = dateFormat.parse(dateStringToParse);
   //result: 9/2/2001 = 999414000000

string to calendar
    SimpleDateFormat fmtDate = new SimpleDateFormat("MM/dd/yyyy");
    Date date = fmtDate.parse(uExpr.getStartDate());
    Calendar myEffectivDate = Calendar.getInstance();
    myEffectivDate.setTime(date);

Calendar to Date
    Calendar rightNow = Calendar.getInstance();
    //Set date display format
SimpleDateFormat formatDate = new SimpleDateFormat("MM/dd/yyyy"); //Print out the Date. You have to convert Calendar to Date to use the format() method System.out.println(formatDate.format(rightNow.getTime()));

More samples:

Calendar sixMonAgo = Calendar.getInstance();
sixMonAgo.add(Calendar.DATE, -180);
System.out.println(formatDate.format(sixMonAgo.getTime()));