Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert string date to java.sql.Date [duplicate]

Tags:

java

sql

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")

like image 743
milesmiles55 Avatar asked Mar 27 '13 20:03

milesmiles55


People also ask

How do I convert a string to a date in sql?

In SQL Server, converting a string to date explicitly can be achieved using CONVERT(). CAST() and PARSE() functions.

Can we convert string to date in java?

We can convert String to Date in java using parse() method of DateFormat and SimpleDateFormat classes.

How convert string to date in java in YYYY MM DD format in java?

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.


2 Answers

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());     }   } 
like image 146
Daniel Kaplan Avatar answered Sep 18 '22 16:09

Daniel Kaplan


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());
like image 21
user3692317 Avatar answered Sep 21 '22 16:09

user3692317