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