Java: java.util.date cannot be cast to java.sql.Time [duplicate] - java

This question already has answers here:
Merge java.util.date with java.sql.Time
(7 answers)
Closed 9 years ago.
I have time converted from millis and now i would like to make an SQL Insert with that time value. I tried this but it is not working:
String INSERT_RECORD ="INSERT INTO PRAVIDLA (CAS,DEN,MIESTNOST,STAV) values(?,?,?,?)";
PreparedStatement pstmt = con.prepareStatement(INSERT_RECORD);
Calendar calendar1 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar1.setTimeInMillis(milli);
Time Cas2 = (Time) calendar1.getTime();
pstmt.setTime(1, Cas2);
pstmt.setInt(2, DEN);
pstmt.setString(3, MIESTNOST);
pstmt.setString(4, STAV);
pstmt.executeUpdate();
Any suggestions please?

java.sql.Time extends java.util.Date, so you cannot simply cast it.
You can try something like this:
Time time = new Time(date.getTime());

The following is what I did when I had a similar problem.
java.util.Date utilDate = new java.util.Date("mm/dd/yyyy");
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
Substitute a real date for "mm/dd/yyyy"

calendar1.getTime() returns a Date object, and Time is a sub-class of Date, so a Date cannot be cast into a Time. You can try this instead:
Time Cas2 = new Time(calendar1.getTimeInMillis());

You can try this. I've not tested the code.
Time time = new Time(calendar.get(Calendar.MILLISECOND)
+ calendar.get(Calendar.ZONE_OFFSET));
You might have to subtract the zone offset.

public class Time extends java.util.Date
It is not possible to cast Date to Time.
You can use this instead:
Time time = new Time(date.getTime())

Related

Insert Date in string format into a database having field type of Date

I am having a date in the following format as string.
String from_date = "2016-09-09";
I need to insert into into a database having date type field using PreparedStatement. I have done it in the following way.
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date fd = formatter.parse(from_date);
select1.setDate(1, fd);
But it is showing the error as
The method setDate(int.java.sql.Date) in the type PreparedStatement is not applicable to the arguments(int,java.util.Date)
You need to use a java.sql.Date when inserting in database. Try the following :
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date fd = formatter.parse(from_date);
java.sql.Date sqlDate = new java.sql.Date(fd.getTime());
select1.setDate(1, sqlDate);
Answered here: Type mismatch: cannot convert from java.util.Date to java.sql.Date
You are trying to use a method that accepts java.sql.Date instead of java.util.Date
Welcome to programming, mind the details
Using java.sql.Date
java.util.Date
Suppose you have a variable endDate of type java.util.Date, you make the conversion thus:
select1.setDate(1, new java.sql.Date(endDate.getTime());

How to convert sql date to java [duplicate]

This question already has answers here:
Using setDate in PreparedStatement
(6 answers)
Closed 6 years ago.
SO i have a table in my database, date declared as date. and now i'm coding in java and i need the DATE to be inputted by the user and store it in my database. how does it work? i mean to convert date in to what? thank you!!
for now this is my code
java.util.Date utilDate = new java.util.Date();
java.sql.Date sqldate = new java.sql.Date(utilDate.getTime());
System.out.print("更新日: ");
String 更新日 = input.nextLine();
If you are using SQL SERVER, the following code will convert your date to SQL Server format.
java.util.Date utilDate = new java.util.Date(); //date that needs conversion
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime()); //converts to SQL date format

How to insert java.util.Date object holding date and time into mysql database [duplicate]

This question already has answers here:
How do I set a full date & time sql using java, and not just the date?
(3 answers)
How to store Java Date to Mysql datetime with JPA
(13 answers)
Closed 8 years ago.
I am using following code to insert a java.util.Date object in MySQL. d1 is date object I'm getting from a function. I tried casting java.util.Date into java.sql.Date but this doesn't save the time part.
String sql = "INSERT INTO abc " +
"VALUES" + "('Zara',?)";
pstmt = conn.prepareStatement(sql);
pstmt.setDate(1, d1);
stmt.executeUpdate(sql);
Any Idea to store Date and time of Date Object in MySQL?
You need to convert java.util.Date instance to java.sql.Date format. and then use it with PreparedStatement.
Change:
pstmt.setDate( 1, d1 );
to:
pstmt.setDate( 1, new java.sql.Date( d1.getTime() );
If the field is of type datetime or timestamp, you have to use
pstmt.setTimestamp( 1, new java.sql.Timestamp( d1.getTime() );

How to send date and time to SQL using java

I am calling a stored procedure in a database.
Two of its parameters requires date and time in sql date format.
String x = new SimpleDateFormat("MM-dd-yyyy").format(new Date()) + " 00:00:00 AM";
String y = new SimpleDateFormat("MM-dd-yyyy").format(new Date()) + " 11:59:00 PM";
Date fromDate = null;
Date toDate = null;
try {
fromDate = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss a").parse(x);
toDate = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss a").parse(y);
} catch (ParseException ex) {
}
CallableStatement proc_stmt = con.prepareCall("{ call someproc(?,?) }");
proc_stmt.setDate(1, (java.sql.Date) fromDate);
proc_stmt.setDate(2, (java.sql.Date) toDate);
I believe if i send just the date(excluding time), the code works, but its of no use to me as the database does not generate correct results.
When i run the above code I get
ClassCastException:java.util.Date cannot be cast to java.sql.Date
Any solution?
Use java.sql.Timestamp class which holds date and time for sql fields, and CallableStatement#setTimestamp:
proc_stmt.setTimestamp(1, new java.sql.Timestamp(fromDate.getTime());
create new object of java.sql date and then pass the java.util date in it.
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
I usually go for along the lines of
proc_stmt.setDate(1, new java.sql.Date(fromDate.getTime()));
Why are you formatting a Date to a String and then parsing it again? You shouldn't need a string representation at all. Avoid string conversions as far as you can - you're not really interested in the text representation of the date; you're just trying to specify a value.
You should be able to use:
// TODO: Consider time zones
Calendar calendar = Calendar.getInstance();
// Clear the time part of the calendar (leaving you with "start of day")
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Timestamp start = new Timestamp(calendar.getTimeInMillis());
// Adjust to "end of day"
calendar.add(Calendar.DATE, 1);
calendar.add(Calendar.MILLISECOND, -1);
Timestamp end = new Timestamp(calendar.getTimeInMillis());
CallableStatement statement = con.prepareCall("{ call someproc(?,?) }");
statement.setTimestamp(1, start);
statement.setTimestamp(2, end);
Note that I've switched to using java.sql.Timestamp instead of java.sql.Date as it looks like you really do want a date and time whereas java.sql.Date only represents a date.
A couple of other points:
If you could use Joda Time, it would make the first part of the code simpler. Joda Time is a much better date/time API in general.
I would suggest you change your stored procedure to use an exclusive end time if possible. That way you can just specify the start of today and the start of tomorrow. You don't need to worry about the granularity of the value, because you can always create abutting but non-overlapping intervals. In particular, I've currently only set end to the end of the day down to the last millisecond - but java.sql.Timestamp

How do I set a full date & time sql using java, and not just the date?

I am trying to set a timestamp in my database using java, however in my table all I get is the date, and no time (i.e., looks like "2010-09-09 00:00:00").
I am using a datetime field on my mysql database (because it appears that datetime is more common than timestamp). My code to set the date looks like this:
PreparedStatement ps = conn.prepareStatement("INSERT INTO mytable (datetime_field) VALUES (?)")
java.util.Date today = new java.util.Date();
java.sql.Date timestamp = new java.sql.Date(today.getTime());
ps.setDate(1, timestamp);
ps.executeUpdate();
How do I set the date to include the time?
Edit: I changed the code as per below, and it sets both the date and the time.
PreparedStatement ps = conn.prepareStatement("INSERT INTO mytable (datetime_field) VALUES (?)")
java.util.Date today = new java.util.Date();
java.sql.Timestamp timestamp = new java.sql.Timestamp(today.getTime());
ps.setTimestamp(1, timestamp);
ps.executeUpdate();
Use java.sql.Timestamp and setTimestamp(int, Timestamp). java.sql.Date is date-only, regardless of the type of the column it's being stored in.
Not exactly sure what you need to use, but
ps.setDate();
expects a column type of Date. So it's normalizing it, removing the time.
Try
ps.setTimetamp();
You could use :
private static String getTimeStamp() {
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return f.format(new Date());
}

Categories

Resources