0

I have a string date in the format DD/MM/YY (16/07/13)
How do I convert this string date to SQL Date format (maintaining the same DD/MM/YY format)
for storing in my Oracle DB.. ??

Code Zero
  • 113
  • 2
  • 9
  • You neither need any `java.sql.Date` nor any particular format for storing a date into a database. Parse into a `LocalDate` using `LocalDate.parse("16/07/13", DateTimeFormatter.ofPattern("dd/MM/yy"))` and see this question for how to store: [Insert & fetch java.time.LocalDate objects to/from an SQL database such as H2](https://stackoverflow.com/questions/43039614/insert-fetch-java-time-localdate-objects-to-from-an-sql-database-such-as-h2) – Ole V.V. Apr 20 '22 at 11:07

2 Answers2

4

Use a SimpleDateFormat:

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy");
String stringWithDate = "16/07/13";
Date theDate = sdf.parse(stringWithDate);
//store theDate variable in your database...

Note that SimpleDateFormat#parse throws ParseException.

UPDATE: Using Java 8 and LocalDate

LocalDate localDate = LocalDate.from(
    DateTimeFormatter.ofPattern("dd/MM/yy")
        .parse(fecha));

If you need to pass this to java.sql time objects, you can see this answer on How to get a java.time object from a java.sql.Timestamp without a JDBC 4.2 driver?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
1

I don't know Java and I'm not super familiar with Oracle, but this may help.

In MS SQL Server I've seen all kinds of bad stuff happen when people try to post stuff using specific date formats. Windows date settings can vary so problems are almost guaranteed. From that point of view your

(maintaining the same DD/MM/YY format)

rings alarm bells

I'm yet to have issues as I usually fall back on handling dates in a "standardised" way.

            'yyyymmdd'  
select CAST('19900506' AS DATETIME)

is very predictable, so if you want predictable you need the oracle equivalent

it also works for date + time

            'yyyymmdd hh:mi:ss.mmm'  
select CAST('19900506 01:01:01.000' AS DATETIME)

Oracle/PLSQL will have similar functions that work in an controllable way. Use these functions to save values correctly then your data can be reliably output in whatever format you specify at the time of retrieval

JamesM
  • 25
  • 6