Question

i am getting input date as String into mm/dd/yyyy and want to convert it into yyyy-mm-dd i try out this code

Date Dob = new SimpleDateFormat("yyyy-mm-dd").parse(request.getParameter("dtDOB"));

No correct solution

OTHER TIPS

OK - you've fallen for one of the most common traps with java date formats:

  • mm is minutes
  • MM is months

You have parsed months as minutes. Instead, change the pattern to:

Date dob = new SimpleDateFormat("yyyy-MM-dd").parse(...);

Then to output, again make sure you use MM for months.

String str = new SimpleDateFormat("dd-MM-yyyy").format(dob);

It should be

SimpleDateFormat("yyyy-MM-dd")

capital M

For More info refer Oracle Docs

As alternative to parsing you can use regex

s = s.replaceAll("(\\d+)/(\\d+)/(\\d+)", "$3-$2-$1");

Ex -

String dob = "05/02/1989";  //its in MM/dd/yyyy
String newDate = null;
Date dtDob = new Date(dob);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

try {
      newDate = sdf.format(dtDob);
} catch (ParseException e) {}

System.out.println(newDate); //Output is 1989-05-02
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FormatDate {

  private SimpleDateFormat inSDF = new SimpleDateFormat("mm/dd/yyyy");
  private SimpleDateFormat outSDF = new SimpleDateFormat("yyyy-mm-dd");

  public String formatDate(String inDate) {
    String outDate = "";
    if (inDate != null) {
        try {
            Date date = inSDF.parse(inDate);
            outDate = outSDF.format(date);
        } catch (ParseException ex) 
            System.out.println("Unable to format date: " + inDate + e.getMessage());
            e.printStackTrace();
        }
    }
    return outDate;
  }

  public static void main(String[] args) {
    FormatDate fd = new FormatDate();
    System.out.println(fd.formatDate("12/10/2013"));
  }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top