This is my database:
Here I have to check the query current date+status=Q information and get the count value.
This is my code:
public class TodayQ {
public int data() {
int count=0;
Date date = new Date(timestamp);
DateFormat dateFormat = new SimpleDateFormat ("yyyy-MM-dd");
System.out.println( dateFormat.format (date));
// count++;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/pro", "root", "");
PreparedStatement statement = con
.prepareStatement("select * from orders where status='Q' AND date=CURDATE()");
ResultSet result = statement.executeQuery();
while (result.next()) {
// Do something with the row returned.
count++; // if the first col is a count.
}
}
catch (Exception exc) {
System.out.println(exc.getMessage());
}
return count;
}
}
Here I have to edit the date is (yyyy-mm-dd) format. Now I got the output. But I wish to use timestamp on my database. So how is converted timestamp to date in Java. How is use that code in my code?
whereas timestamp is a long variable
Assuming timestamp is time in millis, you can use java.util.Calendar to convert timestamp to date time as follows:
You can achieve the same using mysql functions. Hope the following query gives you the desired output.
to print the timestamp in yyyy-mm-dd:
UPDATE
here is a HINT of how you can proceed:
Obviously the now.getTime() returns the actual millisecond the date was captured in the now variable . The mathematics is all up to your implementation from now on.
Remember that the way to get a Calendar object at midnight (10/05/2012 00:00:00) is here Java program to get the current date without timestamp
The date column in the database should be a
TIMESTAMP
orDATE
orTIME
.These are retrieved as
java.sql.Timestamp
orjava.sql.Date
orjava.sql.Time
respectively.All of these classes extend
java.util.Date
.So the data should already be in the format you are asking for.
So there is nothing to do.
Looks like the integer value you are seeing is the UNIX's number of seconds since the start of the Epoch ( which is 1970-01-01T00:00:00Z ) -> http://en.wikipedia.org/wiki/Unix_epoch
I don't know if the mysql JDBC driver will take care of converting this field for you. If it does, the preferred way of getting its value is:
Timestamp extends java.util.Date, so you can use it where regular java.util.Date is expected.
If, for whatever reason this does not produce desired result, then get the column value as
long
and adjust the value to milliseconds. You are in luck here because Java's and UNIX's epochs start at the same time ( Java's is just more precise ).