Is it possible to convert string
"20110210"
to a java.sql.Date
2011-02-10?
I've tried SimpleDateFormat
and I get java.text.ParseException: Unparseable date: "20110210"
What am I doing wrong?
i had new SimpleDateFormat("yyyy-MM-dd") instead of new SimpleDateFormat("yyyyMMdd")
In SQL Server, converting a string to date explicitly can be achieved using CONVERT(). CAST() and PARSE() functions.
We can convert String to Date in java using parse() method of DateFormat and SimpleDateFormat classes.
Parsing String to Date //Instantiating the SimpleDateFormat class SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); Parse/convert the required String to Date object using the parse() method by passing it as a parameter.
This works for me without throwing an exception:
package com.sandbox; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Sandbox { public static void main(String[] args) throws ParseException { SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd"); Date parsed = format.parse("20110210"); java.sql.Date sql = new java.sql.Date(parsed.getTime()); } }
worked for me too:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date parsed = null;
try {
parsed = sdf.parse("02/01/2014");
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
java.sql.Date data = new java.sql.Date(parsed.getTime());
contato.setDataNascimento( data);
// Contato DataNascimento era Calendar
//contato.setDataNascimento(Calendar.getInstance());
// grave nessa conexão!!!
ContatoDao dao = new ContatoDao("mysql");
// método elegante
dao.adiciona(contato);
System.out.println("Banco: ["+dao.getNome()+"] Gravado! Data: "+contato.getDataNascimento());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With