I have a problem when getting a Date object from a ResultSet. In database it has a value (for example 2014-08-01) and after getting it from resultSet, it has another value (2014-08-31). I know that ResultSet's getDate method returns java.sql.Date, but I tried a few solutions, such as:
Date date=new java.util.Date(resultSet.getDate(3).getTime());
or
Date date=resultSet.getTimestamp();
but the problem was the same.
If I try
Date date=resultSet.getDate();
It throws a NullPointerException.
Can anybody explain this?
In your case you were not providing the columnName of the Date field to be retrieved.
This should do the job
while (rs.next()) {
java.sql.Time dbSqlTime = rs.getTime("columnName");
java.sql.Date dbSqlDate = rs.getDate("columnName");
java.sql.Timestamp dbSqlTimestamp = rs.getTimestamp("columnName");
java.util.Date dbSqlTimeConverted = new java.util.Date(dbSqlTime.getTime());
java.util.Date dbSqlDateConverted = new java.util.Date(dbSqlDate.getTime());
System.out.println(dbSqlTimeConverted);
System.out.println(dbSqlDateConverted);
}
iterate over the ResultSetObject get the Date from the ResultSetObject which is java.sql.Date then convert it to java.util.Date
You should use the java.sql.Date instead of java.util.Date, because ResultSet.getDate() returns an SQL Date, and not a Java one.
Related
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());
I am new to java GUI
I have a form for simple data input that saved to mySQL. Among the textboxes I have defined is dateOfBirth.
In mySQL, the dateOfBirth column is type DATE.
When I attempt to save my record, I get incompatible conversions. How Do I handle this? The Date fields are DOR and DOB.
I tried to define a format :
DateFormat df= new SimpleDateFormat("dd/MM/yyyy");
and also changed redefined the var DOR or DOB as String:
String DOB = new String();
then when inserting into database, formatted the var like this:
df.format(DOB)
I still got the error: "Error: Cannot format given object as a Date". What to do?
String query = "INSERT INTO members (MemberID,FamilyName,BaptismName,DateOfRegistration,DateOfBirth,FatherName,MotherName,gender,MemberType,Address,Residence,City,CreatedBy)"
+"VALUES('"+memberID+"','"+familyName+"','"+baptismName+"','"+DOR+"','"+DOB+"','"+fatherName+"','"+motherName+"','"+gender+"','"+memberType+"','"+address+"','"+residence+"','"+city+"','"+operator+"')";
con.UpDate(query);
First of all i would not use that query for the insert. You should use a prepared statement. It's safer against sql injection.
PreparedStatement ps =
connection.prepareStatement("INSERT INTO members (MemberID,FamilyName,BaptismName,DateOfRegistration,DateOfBirth,FatherName,MotherName,gender,MemberType,Address,Residence,City,CreatedBy) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)");
ps.setString(1, memberID); //or the correct type if not String
ps.setString(2, familyName);
ps.setString(3,baptismName);
DateFormat df= new SimpleDateFormat("dd/MM/yyyy"); //this the the format in which the user enters the date in the textbox. they have to input a string like 12/31/2014
java.util.Date date=df.parse(DOB); //DateFormat class has a method called parse which returns a java.util.Date object
ps.setDate(4, new java.sql.Date(date.getTime()));
//PreparedStatement class method setDate takes 2 parameters
//first is the index of the parameter in the prepared statement, and the second
//is java.sql.Date object.
//use constructor of java.sql.Date which takes a long parameter to create this object
//java.util.Date getTime() method returns a long value representing the date object
//so basically you convert string DOB to java.Util.Date,
//then convert java.Util.Date object to java.sql.Date needed by prepared statement
...
ps.executeUpdate();
i am trying to insert Date into database column type Date
getting java.lang.ClassCastException: java.util.Date
code:
Date dateFormatter = (Date) new SimpleDateFormat("dd/MM/yyyy").parse(requiredByDate.toString());
java.sql.Date requiredByDate1 = new java.sql.Date(dateFormatter.getTime());
set to prepared statement:
pstmt.setDate(1, requiredByDate1);
got a error
java.lang.ClassCastException: java.util.Date
pls suggest how to resolve this.
Thanks
Your code and the error message does not match. You have to be using some other version of the code.
You have:
java.sql.Date requiredByDate1 = ...
pstmt.setDate(1, requiredByDate1);
but that code cannot result in
java.lang.ClassCastException: java.util.Date
as it's not java.util.Date.
Your Code Here is :
Date dateFormatter = (Date) new SimpleDateFormat("dd/MM/yyyy").
parse(requiredByDate.toString());
Now Your Date may be either :
1) java.util.Date , OR
2) java.sql.Date , which ultimately is a Sub-class of java.util.Date.
However,
SimpleDateFormat class belongs to java.text package. And you are trying to cast
an object of java.text.SimpleDateFormat to java.util.Date( OR java.sql.Date)
which is why you are getting java.lang.ClassCastException
This question already has answers here:
Converting ISO 8601-compliant String to java.util.Date
(31 answers)
Closed 8 years ago.
For example, I have this String: 06/10/2013 18:29:09. I want to convert this string and put it in a SQL database (as Date).
How can I convert this to an sql date, so that it could be inserted into a database? I want the hours minutes and seconds to remain as well.
I tried the following:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date javaDate = sdf.parse("06/10/2013 18:29:09");
java.sql.Date date = new java.sql.Date(javaDate.getTime());
The problem is here:
java.sql.Date date = new java.sql.Date(javaDate.getTime());
java.sql.Date stores the date part of your timestamp. If you want/need to handle both date and time, use java.sql.Timestamp instead:
java.sql.Timestamp date = new java.sql.Timestamp (javaDate.getTime());
More info:
Date vs TimeStamp vs calendar?
You will use a SimpleDateFormat object to parse the string to java.util.date and then use the getTime() method to instantiate a java.sql.Date.
String input = "06/10/2013 18:29:09";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
java.util.Date dt = sdf.parse(input);
java.sql.Date dtSql = new java.sql.Date(dt.getTime());
If you are working with String type for date input and then you want to save that in a database like MySQL, you should use an appropriate Date Format for it. There's a class called "SimpleDateFormat" which you can use for that purpose. You can find a sample in the following link, also a brief explanation on how it works. Hope it helps.
Example: http://www.java2s.com/Tutorial/Java/0040__Data-Type/SimpleDateFormat.htm
Best Regards.
Here's a simple demo. In a Database table like this.
You can insert into it like this.
//the SQL statement for creating the database table
create table user(id, integer primary key, username varchar(100), date_created varchar(100));
//the java code to insert into the table created above.
try{
String date = new SimpleDateFormat("dd/MM/YYYY HH:mm:ss").format(new Date());
String sql = "insert into user(username, date_created) values('olupotd', '"+date+"')";
int done = statement.executeUpdate(sql);
if(done > 0)
//inserted
else
//not inserted.
}catch(java.sql.SQLException e){}
Hope that helps
I am looking for a way to get today's date and pass to sql table and save there. Call the saved date and do some task with JODA TIME API. The changed Joda time Date to sql table and save there and process continues..
I tried this way,
//prints todays date
java.sql.Date sqlDate = new java.sql.Date(new Date().getTime());
//passes wrong date to the table like 1970-07-01 instead of 2013-03-01
String insert = "INSERT INTO TEST_TABLE VALUES(1,"+sqlDate+")";
pStmt = conn.prepareStatement(insert);
pStmt.executeUpdate();
//converting to joda time
LocalDate ld = new LocalDate(sqlDate);
//some calculations, and how to convert back to sql date?
What I am trying to do here is, A table with 3 columns (id, startdate, finishdate). id will be entered by user, start date should be automatically entered todays date. after some calculations with joda time and finish date will be set to date it is finished.
Code
String insert = "INSERT INTO TEST_TABLE VALUES(2,'"+timestamp+"')";
Error
Data type mismatch in criteria expression
//I have created table using MS access
//the format of the date column is Date/Time.
You Can use Timestamp here. java.sql.Timestamp extends java.util.Date, so anything you can do with a java.util.Date you can also do with a java.sql.Timestamp.
To convert LocalDateTime to Timestamp
Timestamp timestamp = new Timestamp(localDateTime.toDateTime().getMillis());
But if You still want to convert Timestamp into java.sql.Date then use this
java.sql.Date date = new java.sql.Date(timeStamp.getTime());