1

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"));
Ankit Jain
  • 45
  • 1
  • 2
  • 13

5 Answers5

7

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);
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • Hey @Bohemian, congrats for the Diamond :) – Rohit Jain Mar 01 '14 at 07:00
  • thanx but this code not working.. that gives below error Unparseable date: "03/19/2014" at java.text.DateFormat.parse(Unknown Source) – Ankit Jain Mar 01 '14 at 07:06
  • @AnkitJain the cause is plain from the error messags: your input has slashes instead of dashes between the date parts. Try using pattern `"dd/MM/yyyy"` – Bohemian Mar 01 '14 at 07:54
  • @RohitJain hey thanks! I hope to see a diamond next to your name next year. You're a great contributor. I remember when you started you posted high-quality answers, and I thought to myself at the time that you would go far here. I was right. – Bohemian Mar 01 '14 at 07:57
1

It should be

SimpleDateFormat("yyyy-MM-dd")

capital M

For More info refer Oracle Docs

Kamlesh Arya
  • 4,864
  • 3
  • 21
  • 28
1

As alternative to parsing you can use regex

s = s.replaceAll("(\\d+)/(\\d+)/(\\d+)", "$3-$2-$1");
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
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
Arjit
  • 3,290
  • 1
  • 17
  • 18
0
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"));
  }

}
Rahul
  • 25
  • 2