Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java convert date to sql timestamp

Tags:

java

sql

datetime

I'm trying to convert a date (string) extracted from a csv file, convert it to sql timestamp and upload using prepared statement. What I have is:

String test = "8/10/2014 16:59";

DateFormat fromFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm");
fromFormat.setLenient(false);
DateFormat toFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS");
toFormat.setLenient(false);
Date date2 = null;
try {
    date2 = toFormat.parse(test);
} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

//java.sql.Timestamp ts2 = java.sql.Timestamp.valueOf(date2);
//java.sql.Timestamp sqlDate2 = new java.sql.Timestamp(timestamp); 
//sql_statement.setTimestamp(1, ts2);

As you can see my code is messy as I'm trying to solve this problem. I'm always getting an error in eclipse:

java.text.ParseException: Unparseable date: "8/10/2014 16:59"
at java.text.DateFormat.parse(DateFormat.java:357)
at      com.syntronic.client.thread.ORCThreadTejasInv.uploadOracleDBOptical(ORCThreadTejasInv.java:555)
at com.syntronic.client.thread.ORCThreadTejasInv.connectOracleDB(ORCThreadTejasInv.java:170)
at com.syntronic.client.thread.ORCThreadTejasInv.retrieveOracleTejas(ORCThreadTejasInv.java:125)
at com.syntronic.client.thread.ORCThreadTejasInv.run(ORCThreadTejasInv.java:84)
at java.lang.Thread.run(Thread.java:745)

I even try using:

SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" );
String yourformattedDate = sdf.format(test);

and diff error shows up"

Exception in thread "Thread-6" java.lang.IllegalArgumentException: Cannot format given Object as a Date
at java.text.DateFormat.format(DateFormat.java:301)
at java.text.Format.format(Format.java:157)
at com.syntronic.client.thread.ORCThreadTejasInv.uploadOracleDBOptical(ORCThreadTejasInv.java:562)
at com.syntronic.client.thread.ORCThreadTejasInv.connectOracleDB(ORCThreadTejasInv.java:170)
at com.syntronic.client.thread.ORCThreadTejasInv.retrieveOracleTejas(ORCThreadTejasInv.java:125)
at com.syntronic.client.thread.ORCThreadTejasInv.run(ORCThreadTejasInv.java:84)
at java.lang.Thread.run(Thread.java:745)

Anyone can help on why the date is unparseable? and how to convert it to a proper sql timestamp? thank you

like image 664
Arnold Cristobal Avatar asked Apr 14 '26 05:04

Arnold Cristobal


1 Answers

Your fromFormat format specifier is

dd/MM/yyyy hh:mm

but should be

dd/MM/yyyy HH:mm

And change the toFormat to yyyy-MM-dd HH:mm:ss.SSSSSS

Then your parse code should change from

date2 = toFormat.parse(test);

to

date2 = fromFormat.parse(test);
System.out.println(toFormat.format(date2));

And I get the output

2014-10-08 04:59:00.000000
like image 150
Elliott Frisch Avatar answered Apr 16 '26 19:04

Elliott Frisch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!