0

I have a user input a Date string in one format, i can parse it using the corresponding DateFormat and format it using another (DB) DateFormat to format the Date.

However, using the DB DateFormat, i cannot convert it to the corresponding Date object.

My code:

String userSpecifiedDate = "Fri Oct 12 15:28:04 UTC 2018";
SimpleDateFormat userSpecifiedDateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss 'UTC' yyyy");
SimpleDateFormat DBDateFormat = new SimpleDateFormat("dd-MMM-yy hh.MM.ss.SSSSSS a");

Date userDateFormat = userSpecifiedDateFormat.parse(userSpecifiedDate);
System.out.println("User specified date in original format : " + userDateFormat);
// prints just fine : 'Fri Oct 12 15:28:04 PDT 2018' 

String userSpecfiedDateInDBFormat = DBDateFormat.format(userDateFormat);
System.out.println("User specified Sting in DB format : " + userSpecfiedDateInDBFormat);
// prints: '12-Oct-18 03.10.04.000000 PM' (works for me, although see the minutes are wrong)

Date uss = DBDateFormat.parse(userSpecfiedDateInDBFormat);
System.out.println("User specified Date in DB format : " + uss);
// prints : 'Fri Oct 12 15:00:04 PDT 2018' ??

I was expecting it to print the date in the DB DateFormat, same as '12-Oct-18 03.10.04.000000 PM'

I need the Date in that format since i am going to use that Date Object in the JPA to compare dates in a @NamedQuery.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • An RTFM question really - Java doc: https://docs.oracle.com/javase/8/docs/api/java/util/Date.html#toString-- The toString() method is fixed to use the "dow mon dd hh:mm:ss zzz yyyy" format. – Sunil Dudani Oct 12 '18 at 19:14
  • I recommend you avoid the `SimpleDateFormat` class. It is not only long outdated, it is also notoriously troublesome. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). And don’t worry, this question has been asked many times before. On the other hand: search before posting a question, you’ll quote often get a good answer faster that way. – Ole V.V. Oct 13 '18 at 05:28
  • Also, while JPA is not my home field, I am under the impression that it accepts proper date-time objects, so you should not pass date-times as strings to it. Depending on what is possible and appropriate for your situation pass it an `Instant`, `OffsetDateTime`, `ZonedDateTime` or `LocalDateTime`. And then don’t worry about format at all. – Ole V.V. Oct 13 '18 at 05:39

1 Answers1

0

An RTFM question really - Java doc: docs.oracle.com/javase/8/docs/api/java/util/… The toString() method is fixed to use the "dow mon dd hh:mm:ss zzz yyyy" format