Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

    }
}
like image 857
vibhor Avatar asked Feb 23 '26 03:02

vibhor


2 Answers

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.

like image 100
Jops Avatar answered Feb 25 '26 15:02

Jops


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

like image 28
mki Avatar answered Feb 25 '26 16:02

mki