aspose file tools*
The moose likes JDBC and the fly likes problem with java.util.Date() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC
Bookmark "problem with java.util.Date()" Watch "problem with java.util.Date()" New topic
Author

problem with java.util.Date()

Nikhil Chavan
Greenhorn

Joined: Jun 19, 2008
Posts: 1
Hello everyone, here is one problem I am facing while using java.util.Date() class.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.format(new java.util.Date());
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
sd.format(new java.util.Date());

Statement stmt = Conn.createStatement(); // Conn object is already created
String query = "select sum(ctotal) from creg where date_time between '"+sd.format(new java.util.Date())+"' and '"+sdf.format(new java.util.Date())+"'";
ResultSet rs = stmt.executeQuery(query);
if(rs.next())
{
totalCash = rs.getFloat(1);
}

Here in this code, I'm not getting the proper value for "new java.util.Date()" when using JSP with Tomcat5.5 (jakarta-tomcat-5.5.9)??
I cant trace what's the exact problem.
All suggestion are welcome !
Thanks.
Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 30324
    
150

Nikhil,

You should use a PreparedStatement rather than a Statement to insulate your code from the format the database wants a Date in. Then your query looks like:
select sum(ctotal) from creg where date_time between ? and ?

and you can call:
java.util.Date now = new java.util.Date();
preparedStatement.setDate(1, new java.sql.Date(now.getTime()));


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 30324
    
150

I'm going to move this to our JDBC form since it is about data access.

And welcome to JavaRanch!
Rene Larsen
Ranch Hand

Joined: Oct 12, 2001
Posts: 1179

Originally posted by Jeanne Boyarsky:
Nikhil,

You should use a PreparedStatement rather than a Statement to insulate your code from the format the database wants a Date in. Then your query looks like:
select sum(ctotal) from creg where date_time between ? and ?

and you can call:
java.util.Date now = new java.util.Date();
preparedStatement.setDate(1, new java.sql.Date(now.getTime()));


And if you also want to compare on the date AND time, then you need to use java.sql.Timestamp instead of java.sql.Date in the preparedStatement.

java.util.Date now = new java.util.Date();
preparedStatement.setTimestamp(1, new java.sql.Timestamp(now.getTime()));
[ August 30, 2008: Message edited by: Rene Larsen ]

Regards, Rene Larsen
Dropbox Invite
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: problem with java.util.Date()