vibhor
vibhor

Reputation: 59

Converting string to type 'Date'

I have used the Calendar class to get the current Date. Now I want to convert that date to Date format so that it can be stored in database with format "yyyy-mm-dd". I tried to convert it with using SimpleDate format but I got error. The code is as follows. Help. Thanks in advance.

class dateDemo
{
    public static void main(String args[])
    {


    String stringdate ;
    SimpleDateFormat sdf;
    String year,month,day;  

    Calendar currentDate;
    Date validity;

    currentDate = Calendar.getInstance();

    year = "" + currentDate.get( Calendar.YEAR );
    month = "" + currentDate.get( Calendar.MONTH );
    day = "" + currentDate.get( Calendar.DAY_OF_MONTH );


    stringdate = year+"/"+month+"/"+day;


    sdf = new SimpleDateFormat("yyyy-mm-dd");

    try
    {
    validity = sdf.parse ( stringdate );
    }

     catch(Exception e)
    {
            System.out.println(""+e);
    }

    System.out.println("Current Date is:"+stringdate);


    System.out.println("Date is"+validity);             

    }
}

Upvotes: 3

Views: 420

Answers (3)

cahen
cahen

Reputation: 16636

Database connectors can handle dates, don't convert it to String, it's not a good practice.

You could rewrite the code like this:

PreparedStatement pstmt = connection.prepareStatement("INSERT INTO MyTable values(?)");
java.sql.Date sqlDate = new java.sql.Date(currentDate.getTime()); 
pstmt.setDate(1, sqlDate)

Upvotes: 1

mki
mki

Reputation: 635

Read the answer of Roxinus for the correct code.

I recommand you to always look at the documentation of Java API when you write code. It is extremely usefull and you find often how to use the code : Java API documentation

Upvotes: 1

Jops
Jops

Reputation: 22705

I ran your code and got java.text.ParseException. Just to remove the error, you can simply change the "/" to "-" in your program BUT it won't give you the correct date.

Try this revised solution, in String, java.util.Date and java.sql.Date formats:

class dateDemo {

    public static void main(String args[]) {

        SimpleDateFormat sdf;
        String validity = "";
        Date validityDate = null;
        java.sql.Date validateDateSql = null;

        Date currentDate = Calendar.getInstance().getTime();
        sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            validity = sdf.format(currentDate);
            validityDate = sdf.parse(validity);
            validateDateSql = new java.sql.Date(validityDate.getTime());                    
        } catch (Exception e) {
            System.out.println("" + e);
        }
    }
}

Take note of the SimpleDateFormat setting: yyyy-MM-dd, not yyyy-mm-dd. It matters.

Upvotes: 2

Related Questions