-2

I am trying to convert string to Date, but I am not able to get the format that I want. My code goes like this:

String inputDate ="1948-06-29";
SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd");
Date date = simpleDate.parse(inputDate); 
System.out.println("Output : " + date); // Output: Tue Jun 29 00:00:00 CDT 1948

I want the date to print out the same format as the input string like this "1948-06-29"

please let me know if there is any approach to solve this.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
zel
  • 11
  • 1
  • Why did you tag this with c++? And arrays? And Spring? – f1sh Jun 18 '22 at 00:13
  • Just use the same `simpleDate`, but use `format` instead of `parse`. – f1sh Jun 18 '22 at 00:15
  • 2
    Don’t use the effectively deprecated java.util date/calendar classes, makes use of the newer, fixed, improved java.time apis – MadProgrammer Jun 18 '22 at 00:23
  • 1
    `LocalDate.parse( "1948-06-29" ).toString()`. You are using terrible date-time classes that were supplanted years ago by the modern *java.time* classes defined in JSR 310. – Basil Bourque Jun 18 '22 at 02:00
  • I too strongly recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead as @BasilBourque said use `LocalDate` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Jun 18 '22 at 06:21
  • Well, the simple and not-recommended way would be to print your original string. What is your own reason for not wanting to do that? The answer could help us guide you even better. – Ole V.V. Jun 18 '22 at 06:32
  • @OleV.V. I was doing encryption on date of birth and the encrypted value is string with this format "yyyy-MM-dd". the problem is in my oracle db the data type is Date. So ,I want to change the encrypted value from string to Date data type and don't wan't to change my encrypted format. – zel Jun 18 '22 at 21:23
  • Thanks. Just pass a `LocalDate` to Oracle (you are correct, not a `String`). Don't worry about how that `LocalDate` prints. Oracle will use its own internal binary format anyway. – Ole V.V. Jun 19 '22 at 05:37

1 Answers1

0

Use SimpleDateFormat#format:

System.out.println("Output : " + simpleDate.format(date));
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • 1
    I beg to differ. Even though the question assumed otherwise, no one should use `SimpleDateFormat`. It’s a notorious troublemaker of a class and long outdated. – Ole V.V. Jun 18 '22 at 06:23
  • Also you are not giving what was requested: “I am trying to convert string to Date, but I am not able to get the format that I want.” And “I want the date to print out the same format as the input string …” (my italics). Because those requirements are impossible. A `Date` hasn’t got a format. – Ole V.V. Jun 18 '22 at 09:39