java.util.Date cannot be cast to java.sql.Date [duplicate] - java

This question already has answers here:
java.util.Date vs java.sql.Date
(7 answers)
Closed 5 years ago.
I am trying to insert Date into Database but I am getting error as java.util.Date cannot be cast to java.sql.Date.
Please help.
String next_dt = req.getParameter("NextDate");
DateFormat dtFmt = null;
dtFmt = new SimpleDateFormat("yyyy-MM-dd");
dtToday = (Date) dtFmt.parse(next_dt);

You have imported java.sql.Data. But dtFmt.parse(next_dt); returns an object of type java.util.Date so you have to change
import java.sql.Date;
to
import java.util.Date;

DateFormat.parse() returns a java.util.Date, and you're trying to illegally cast it to a java.sql.Date.
Assuming you continue to import java.sql.Date, you can successfully assign the variable like so:
dtToday = new Date(dtFmt.parse(next_dt).getTime());

You should use java.sql.Timestamp or java.sql.Date instead of java.util.Date
Problem with java.sql.Date is that it will not store time. So using Timestamp is the approach i always take. As it is the child class of java.util.date it is compatible with both date and timestamp columns in DB.

Add following lines - as it needs to be a sql Date and not util date
java.sql.Date sqlDate = new java.sql.Date(dtToday.getTime());
//now insert this sqlDate

public static java.sql.Date convertFromJAVADateToSQLDate(
java.util.Date javaDate) {
java.sql.Date sqlDate = null;
if (javaDate != null) {
sqlDate = new Date(javaDate.getTime());
}
return sqlDate;
}
As the name of the class is same use should give fully qualified name(FQN) of both classes you also can use format method to convert date to proper SQL format date.
public static String toMysqlDateStr(Date date) {
String dateForMySql = "";
if (date == null) {
dateForMySql = null;
} else {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateForMySql = sdf.format(date);
}
return dateForMySql;
}

Related

Compare date with current date in java using sql

I am trying to compare a SQL date with the current date.
I figured out how to compare two SQL dates but I couldn't extract the current date.
java.sql.Date xxx = new java.sql.Date(jdatechooser1.getDate().getTime());
java.sql.Date yyy = new java.sql.Date(jdatechooser2.getDate().getTime());
if (yyy.after(xxx)) {
System.out.println("ok");
}
Uses the system date instead: System.currentTimeMillis()
java.sql.Date dateToBeChecked= new java.sql.Date(jdatechooser1.getDate().getTime());
java.sql.Date systemDate = new java.sql.Date(System.currentTimeMillis());
if(dateToBeChecked.after(systemDate)){
System.out.println("ok");
}
But since it's long values you don't need to transform anything to an object and can do this instead:
if(jdatechooser1.getDate().getTime() > System.currentTimeMillis()){
System.out.println("ok");
}
At first you must create a java.util.Date object with empty constructor. Then give the long value which can be get by getTime() method, to the java.sql.Date constructor.
java.sql.Date date = new java.sql.Date(new java.util.Date().getTime());

java.text.parseException: unparseable date 1994-09-09 [duplicate]

This question already has answers here:
How to convert java.util.Date to java.sql.Date?
(17 answers)
Closed 7 years ago.
I am trying to send a date value from my java program into an oracle sql database. But I keep getting the error: java.text.parseexception: unparseable date.
I set the date format as:
SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH);
java.sql.Date date = (java.sql.Date)df.parse(dob_text.getText());
I have set my database with the same date format.
And try to send the date through a prepared statement like so:
ps.setDate(3, date);
I am entering a date 1994-09-09. That's the correct date format for the one I declared right? Is there something wrong with my java formation code? Has anyone else had this problem? Any help would be much appreciated
This should work, I corrected 2 errors :
First of all, the format should have been yyyy-MM-dd since that's the format of your input.
Then, you can not implicitely cast java.util.Date to java.sql.Date, you need to use the java.sql.Date constructor and java.util.Date#getTime(). See here
Solution
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
java.sql.Date SQLDate = new java.sql.Date(df.parse(dob_text.getText()).getTime());
Change your format to yyyy-MM-dd.
I just wrote this program and it works fine. Make sure you aren't getting some other error now.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
public class DateFormatDemo
{
public static void main(String[] args) throws ParseException
{
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
System.out.println(df.parse("1994-09-09"));
}
}
Your first try probably threw the exception you mentioned because of the wrong format as Josh pointed out. After correcting this the next problem occurs:
A java.sql.Date is NOT a java.util.Date. So you cannot just typecast the outcome of the df.parse, which is a java.util.Date.
And third: If you provide the pattern to the SimpleDateFormat you can omit the locale.
Following code runs without errors:
String input = "1994-09-09";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date date = df.parse(input);
System.out.println( date);
java.sql.Date sqlDate = new java.sql.Date( date.getTime() );
System.out.println( sqlDate);

Convert java.util.Date to java.sql.Date with 'yyyy-mm-dd hh mm ss' [duplicate]

This question already has answers here:
java sql date time
(2 answers)
How to convert java.util.Date to java.sql.Date?
(17 answers)
Closed 7 years ago.
I need to pass json string to one of the rest web service. There is a property called 'amortizationdate' which will have format 'yyyy-mm-dd hh mm ss'.
for e.g. {amortizationdate:2015-07-31 00:00:00}
we are having AmortizationVO.java with a property amortizationdate.
for e.g
private java.sql.Date amortizationDate.
public void setAmortizationDate(java.sql.Date date){
}
We need to set the date by calling setAmortizationDate(..date) method and using Jackson to convert AmortizationVO.java to Json.
but in JSON I m getting {amortizationdate:2015-07-31}. But expected result should be with timestamp.(amortizationdate:2015-07-31 00:00:00)
note: I don't want to use util date in my Value Object.
Pls help.
What I've tried:
java.util.Date utilDate = new java.util.Date();
java.sql.Timestamp sq = new java.sql.Timestamp(utilDate.getTime());
ExcelEntityAddressVO entityAddressVO = new ExcelEntityAddressVO();
entityAddressVO.setAmortizationDate(new java.sql.Date(sq.getTime()));
This is my JSON:
{
"amortizationdate" : "2015-07-31",
}
You don't want java.sql.Date - it doesn't keep time, use java.sql.Timestamp
You can try this:
import java.sql.Timestamp;
public class Test {
public static void main(String[] args) {
java.util.Date utilDate = new java.util.Date();
System.out.println("utilDate:" + utilDate);
Timestamp ts = new Timestamp(utilDate.getTime());
System.out.println(ts);
}
}

How to cast java.util.date to java.sql.date? [duplicate]

This question already has answers here:
How to convert java.util.Date to java.sql.Date?
(17 answers)
Closed 8 years ago.
Date date = new Date();
DateFormat dt = new SimpleDateFormat("yyyy-MM-dd");
try {
date = dt.parse("2014-03-14");
} catch (ParseException parseException) {
}
orderBean.setDate((java.sql.Date) date);
when I try to cast util.date to sql.date using above code an error occurs as below. I am using mysql data base to store a data.
can anyone help me?
Mar 14, 2014 11:16:44 AM gui.salespot jButton1ActionPerformed
SEVERE: null
java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Date
No. You cannot cast different type of Objects like that.
instead you can get the time which is long and use it.
java.sql.Date sDate = new java.sql.Date(date.getTime());
try this way
Date date = new Date();
java.sql.Date d=new java.sql.Date(date.getTime());
java.sql.Date extends from java.util.Date, so you can case java.sql.Date to java.util.Date but not the other way round.
Try using...
orderBean.setDate(new java.sql.Date(date.getTime()));
Instead...
java.util.Date is superclass of java.sql.Date you can not type cast it by this way.
try with - java.sql.Date#Date(long)
Snippet -
java.sql.Date sqlDate = new java.sql.Date(date.getTime())
look like simple....
public class MainClass {
public static void main(String[] args) {
java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
System.out.println("utilDate:" + utilDate);
System.out.println("sqlDate:" + sqlDate);
}
}
explains it. The link is click
Use this answer to convert date.
java.util.Calendar cal = Calendar.getInstance();
java.util.Date utilDate = new java.util.Date(); // your util date
cal.setTime(utilDate);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
java.sql.Date sqlDate = new java.sql.Date(cal.getTime().getTime()); // your sql date
System.out.println("utilDate:" + utilDate);
System.out.println("sqlDate:" + sqlDate);
For your concern copy my code.
Date date = new Date();
DateFormat dt = new SimpleDateFormat("yyyy-MM-dd");
try {
date = dt.parse("2014-03-14");
} catch (ParseException parseException) {
}
orderBean.setDate(new java.sql.Date(date.getTime()));
Check this reference.. Thanks..

SimpleDateFormat gives java.lang.classcastexception: java.util.date

String str = "13/06/2011";
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = (Date)formatter.parse(str);
I guess that your Date class is actually a java.sql.Date.
What does your import statement say? Are you importing some other class (for example java.sql.Date) by accident? What does the compiler say when you remove the class cast (which should not be there)?
DateFormat.parse() returns an instance of java.util.Date and not java.sql.Date.
In order to convert from java.util.Date to java.sql.Date, I do the following:
java.util.Date fromDate = df.parse(fromdate1);
java.sql.Date sqlDate = new java.sql.Date(fromDate.getTime());

Categories