-3

So I have a Date variable which I formatted using the following code:

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

Date currentDate = new Date();
String date = format.format(currentDate);

I then put the String 'date' into my database.

Now: I have to pull it out of the database. It comes out as, of course, a String in the format shown above.

My question is how do I turn this String into a date variable? I'm very much struggling to find the most efficient way.

Thank you.

S. Rhodes
  • 1
  • 1
  • 1
    Have you tried `parse`? – Marvin May 05 '18 at 00:01
  • @Marvin I looked at parse but I can't imagine that takes the same format as my SimpleDateFormat above? How will it recognise the input format? – S. Rhodes May 05 '18 at 00:02
  • Look at [`SimpleDateFormat.parse(String)`](https://docs.oracle.com/javase/8/docs/api/java/text/DateFormat.html#parse-java.lang.String-) – Elliott Frisch May 05 '18 at 00:04
  • 2
    *"I then put the String 'date' into my database."* - Why!? JDBC can support the transparent transformation of date/time values in native form, why would you use a `String` and a `String` without reference to the timezone it was created!? – MadProgrammer May 05 '18 at 00:16
  • 1
    For example, using `PreparedStatement`, you might be able to use `preparedStatement.setObject(1, LocalDateTime.now());` - this assumes your column supports date/time values – MadProgrammer May 05 '18 at 00:18
  • I recommend you stay away from the `SimpleDateFormat` class and its long outdated friends (like `Date`). It’s troublesome. Instead use [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/), and its `DateTimeFormatter`. – Ole V.V. May 05 '18 at 14:53

2 Answers2

0

You can use a SimpleDateFormatter to parse a String in to a Date.

RyanJ
  • 158
  • 10
0

Simply use DateFormat#parse:

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

Date inputDate = new Date();
System.out.println("inputDate: " + inputDate);

String dateString = format.format(inputDate);
System.out.println("dateString: " + dateString);

Date parsedDate = format.parse(dateString);
System.out.println("parsedDate: " + parsedDate);

Sample output:

inputDate: Fri May 04 23:56:54 GMT 2018
dateString: 2018-05-04 23:56:54
parsedDate: Fri May 04 23:56:54 GMT 2018

See working code on ideone.com.

Marvin
  • 13,325
  • 3
  • 51
  • 57