-3

I need to convert a java string in a date format to a new date format to send it to my sql-server. Currently, my Java date is Jul 17 2018 14:22:58, and I need it to look like 2018-07-17 14:22:58. So I created this:

String oldTime = "Jul 17 2018 14:22:58";

SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD HH:MM:SS");
Date formattedDate = sdf.parse(oldTime);

I am getting errors that my oldTime is unparseable. Did I do this wrong?

user3334871
  • 1,251
  • 2
  • 14
  • 36
  • 1
    Your string starts with "Jul". Does that look like something that matches YYYY? Read the javadoc. That's what it's for. And no, SQL server doesn't expect a string in another format. Use the right type (a LocalDateTime, or a java.sql.Timestamp), and learn how to use prepared statements. Again, reading the documentation helps. – JB Nizet Jul 17 '18 at 21:43
  • Incorrect format. You need to provide format for the oldTime to parse it into Date. Then you need to format Date with "YYYY-MM-DD HH:MM:SS" – Pavel Molchanov Jul 17 '18 at 21:43
  • 1
    Can we also step past the use of (effectively deprecated) `SimpeDateFormat` and move on to the new date/time APIs – MadProgrammer Jul 17 '18 at 22:59

1 Answers1

1

You need to use a format string that matches your date string:

String oldTime = "Jul 17 2018 14:22:58";

SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy HH:mm:ss");
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • I guess my question then becomes how do I convert the date to the other format? I assume I do that once I create the Date object? – user3334871 Jul 17 '18 at 21:47
  • 1
    @user3334871 "dates" don't have a prescribed format of their own - you need to use a new formatter to convert the date value back to a `String` - maybe you should start with [the Java date/time tutorials](https://docs.oracle.com/javase/tutorial/datetime/iso/index.html) – MadProgrammer Jul 17 '18 at 23:00