What is the correct format for date filtering - JDBC to SQL
I have been trying to use the following with an MS-Access DB
SELECT doctorbusiness.dateofreport,
doctorbusiness.patientname,
doctorbusiness.labcomm,
doctorbusiness.xcomm,
doctorbusiness.spccomm,
doctorbusiness.ecgcomm
FROM doctorbusiness
WHERE doctorbusiness.doctorname = '"+selectedDoc+"'
AND (( doctorbusiness.dateofreport >= # "+sd+" # )
AND ( doctorbusiness.dateofreport <= # "+ed+" # ))
selectedDoc is in String and sD and eD in date format.
The query runs fine in MS-Access but gives the following exception :
net.ucanaccess.jdbc.UcanaccessSQLException: unknown token:
UPDATE
public void printDoctorIncome() {
Date startDate = easypath.docB_startDate_jxdp.getDate();
Calendar calSD = Calendar.getInstance();
calSD.setTime(startDate); // convert your date to Calendar object
int daysToDecrement = -1;
calSD.add(Calendar.DATE, daysToDecrement);
Date real_StartDate = calSD.getTime();
SimpleDateFormat sdF1 = new SimpleDateFormat("dd-MM-yyyy");
String sD = sdF1.format(real_StartDate);
JOptionPane.showMessageDialog(null, sD);
Date endDate = easypath.docB_endDate_jxdp.getDate();
Calendar calED = Calendar.getInstance();
calED.setTime(endDate); // convert your date to Calendar object
int daysToIncrement = +1;
calED.add(Calendar.DATE, daysToIncrement);
Date real_endDate = calED.getTime();
SimpleDateFormat sdF2 = new SimpleDateFormat("dd-MM-yyyy");
String eD = sdF2.format(real_endDate);
JOptionPane.showMessageDialog(null, eD);
String selectedDoc = easypath.drname_jlist.getSelectedValue().toString();
String sql = "SELECT doctorBusiness.dateofreport, doctorBusiness.patientName, doctorBusiness.labComm, doctorBusiness.xComm, doctorBusiness.spcComm, doctorBusiness.ecgComm FROM doctorBusiness WHERE doctorBusiness.doctorname ='"+selectedDoc+"' AND (doctorBusiness.dateofreport >= ?"+sD+"? AND doctorBusiness.dateofreport <= ?"+eD+"?)";
try {
conn = connectDB.getConnection();
psmt = conn.prepareStatement(sql);
rs = psmt.executeQuery();
doctorIncome.docIncomePrint_table.setModel(DbUtils.resultSetToTableModel(rs));
doctorIncome dI = new doctorIncome();
dI.setVisible(true);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error");
e.printStackTrace();
}
}
This is the code I am using
With JDBC better way to do it is use setDate/Time/Timestamp methods of PreparedStatement. And you shouldn't care about concrete DB's date format.
Date dateFrom = ...
Date dateTo = ...
String sql = "... where myDate >= ? and myDate <= ? "
preparedStatement.setDate(1, dateFrom);
preparedStatement.setDate(2, dateTo);
Using a PreparedStatement is a good idea. But you can also use either #MM/dd/yyyy# or #yyyy-MM-dd# (with or without hours:minutes:seconds).
Related
So my problem is that I want to allow the user to change the shipping date of the product according to what they want. So what I did is that I collect the year,month and day input from the user and convert it into the date format that SQL required. All the input was fine but whenever I wanted to update the shipping date, it doesn't update and neither shows the error.
I used the input that I got from the user to set the Calendar class's year,month and date. Then I converted the date into the java.util.Date before I could convert it into java.sql.Date
//sql query
private static final String UPDATESHIPPINGDATE = "UPDATE book SET shippingDate = ? WHERE orderID = ? ";
//Required format for SQL
private static final String DATE_FORMAT_NOW = "yyyy-MM-dd";
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
//The method
public void updateShippingDate(int orderID, int year,int month,int day){
try(Connection con = DBConnection.getConnection();
PreparedStatement stmtUpdate = con.prepareStatement(UPDATESHIPPINGDATE);
PreparedStatement stmtShippingDate = con.prepareStatement(GETSHIPPGINGDATE);
){
cal.set(Calendar.YEAR,year);
cal.set(Calendar.MONTH,(month-1));
cal.set(Calendar.DATE,(day-1));
Date dateConvert = cal.getTime();
java.sql.Date shippingDate = new java.sql.Date(dateConvert.getTime());
stmtUpdate.setInt(1,orderID);
stmtUpdate.setDate(2,shippingDate);
stmtUpdate.executeUpdate();
stmtShippingDate.setInt(1,orderID);
ResultSet result = stmtShippingDate.executeQuery();
while (result.next()){
System.out.println("Your new shipping date: " + result.getDate("shippingDate"));
}
}catch (Exception e){
System.out.println(e);
}
}
Expected: 2019-06-20(updated output)
The output was: 2019-06-24(old output)
How to obtain Date values from database then set it as a string. Can anyone tell me why the below code is not working properly? This is the portion giving trouble:
// Date d = rs.getDate("PatientBirthDate");
// DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
// String date = df.format(d);
while (rs.next()) {
pid.setText(String.valueOf(rs.getInt("PatientID")));
ssn.setText(rs.getString("PatientSSN"));
firstname.setText(rs.getString("PatientFname"));
lastname.setText(rs.getString("PatientLname"));
gender.setText(rs.getString("PatientGender"));
// dob.setText(date);
streetnum.setText(rs.getString("PatientStreetNo"));
streetname.setText(rs.getString("PatientStreetName"));
city.setText(rs.getString("PatientCity"));
state.setText(rs.getString("PatientState"));
zip.setText(rs.getString("PatientZip"));
homephone.setText(rs.getString("PatientHomePhone"));
cellphone.setText(rs.getString("PatientCellPhone"));
email.setText(rs.getString("PatientEmailAddress"));
inspolicy.setText(rs.getString("InsurancePolicyNumber"));
inscompany.setText(String.valueOf(rs.getInt("InsuranceCompID")));
}
Why you are reading the date outside the loop?
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
while (rs.next()) {
pid.setText(String.valueOf(rs.getInt("PatientID")));
ssn.setText(rs.getString("PatientSSN"));
firstname.setText(rs.getString("PatientFname"));
lastname.setText(rs.getString("PatientLname"));
gender.setText(rs.getString("PatientGender"));
Date d = rs.getDate("PatientBirthDate");
String date = df.format(d);
dob.setText(date);
streetnum.setText(rs.getString("PatientStreetNo"));
streetname.setText(rs.getString("PatientStreetName"));
city.setText(rs.getString("PatientCity"));
state.setText(rs.getString("PatientState"));
zip.setText(rs.getString("PatientZip"));
homephone.setText(rs.getString("PatientHomePhone"));
cellphone.setText(rs.getString("PatientCellPhone"));
email.setText(rs.getString("PatientEmailAddress"));
inspolicy.setText(rs.getString("InsurancePolicyNumber"));
inscompany.setText(String.valueOf(rs.getInt("InsuranceCompID")));
}
hi i have to convert timestamp to date after check the query and return the count value.
my database have date(1344399208,1344399269),status(Q,Q).
This is my code:
public class GetCurrentDateTime {
public int data(){
int count=0;
java.sql.Timestamp timeStamp =new Timestamp(System.currentTimeMillis());
java.sql.Date date = new java.sql.Date(timeStamp.getTime());
System.out.println(date);
//count++;
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/xcart-432pro","root","");
PreparedStatement statement = con.prepareStatement("select * from xcart_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 the date is saved in timestamp format.but i like to convert date(yyyy-mm-dd) format.its done successfully.ya i got the output is 2012-08-08.but i have to check the query today date+status=Q .so how is that date is save in variable and call that variable in query.so how is wrote query for above condition.after check the condition and display the returns count value on my tomcat console.How is to do.please help me
Partial Answer to your Question
Date Examples
Examples borrowed from Code Ranch and SO posts
// Get system time
Timestamp SysTime = new Timestamp(System.currentTimeMillis());
java.util.Date UtilDate = new java.util.Date(Systime.getTime());
java.sql.Date SQLDate = new java.sql.Date(Systime.getTime());
// Date + Time + Nano Sec
System.out.println(SysTime);
// Date + Time
System.out.println(UtilDate);
// Date
System.out.println(SQLDate);
Formatting Dates
// Apply Format
Date InDate = SQLDate; // or UtilDate
DateFormat DateFormat = new SimpleDateFormat("yyyy MM dd");
String DisplayDate = DateFormat.format(InDate);
System.out.println(DisplayDate);
Please note that I am new to java, hence verify if it works.
Comparing dates
See this SO post:
How to compare dates using Java
To convert date to the date format specified:
int timestamp = 1231342342342; // replace with timestamp fetched from DB
Date date = new Date(timestamp);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
String dateString = sdf.format(date); //convert to yyyy-mm-dd format
From what I understand from the edit, you want the query to be something like this:
PreparedStatement statement = con.prepareStatement("select * from xcart_orders where status='Q' AND date='"+dateString+"'");
I'm assuming that the date is stored in string format in the DB since you asked it to be converted into a particular format.
From comments:
To get midnight date:
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
To get all entries within a 24 period:
"select * from xcart_orders where status='Q' AND date between " + cal.getTimeInMillis() + " and " + (cal.getTimeInMillis() + 86400000l);
Good Day.
I've got another problem related to Jtable.
I want to change the row color of a table if the date inside column (expiry) exceeds or is equal to the current date.
I tried this code but i get an error: java.lang.NumberFormatException: For input string: "2012-03-15"
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
String expDateString = sdf.format(cal.getTime());
System.out.println(expDateString);
Double date = Double.parseDouble(expDateString);
Double val = Double.parseDouble(tableSummary.getModel().getValueAt(row, 6).toString());
for(int i=0; i<=tableSummary.getRowCount()-1; i++){
if(val >= date){
renderer.setBackground(red);
}
}
Thanks!
here's a new code:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
String expDateString = sdf.format(cal.getTime());
Date today = new Date(expDateString);
System.out.println("ang churva is " + today);
Date given = new Date(tableSummary.getModel().getValueAt(row, 6).toString());
for(int i=0; i<=tableSummary.getRowCount()-1; i++){
if(today.compareTo(given)>=0){
renderer.setBackground(red);
}
}
but i get this exception: java.lang.IllegalArgumentException at Date today = new Date(expDateString);
Use the code
DATEDIFF('d',NOW(),exdate)
in your resultset query. It will return the difference. Alter it possibly to match your needs.
You can't cast a date string in a double
Double date = Double.parseDouble(expDateString); //does not work!
Simple example of how you can compare you dates. Note that if the objects in your JTable already are Dates, you don't need all the parsing, which would make your life easier.
The output of the code below is:
expiryDate=2012-03-15
tableDateOK=2012-03-12
tableDateExpired=2012-03-18
tableDateOK>expiryDate = false
tableDateExpired>expiryDate = true
Code:
public static void main(String args[]) throws ParseException {
String expiryDate = "2012-03-15";
String tableDateOk = "2012-03-12";
String tableDateExpired = "2012-03-18";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("expiryDate="+expiryDate);
System.out.println("tableDateOK="+tableDateOk);
System.out.println("tableDateExpired="+tableDateExpired);
System.out.println("tableDateOK>expiryDate = " + sdf.parse(tableDateOk).after(sdf.parse(expiryDate)));
System.out.println("tableDateExpired>expiryDate = " + sdf.parse(tableDateExpired).after(sdf.parse(expiryDate)));
}
line Double date = Double.parseDouble(expDateString);
this cannot work because string "2012-03-15" is simply not a valid double value.
I do not understand why you are trying to compare two double values:
if you have Date in table, use Date.after() and Date.before() to find out, whether your date is before or after now.
if you have String in table, use the SimpleDateFormat.parse() to get Date from it and do point 1
public String compareDate( Request request ) throws ParseException {
Date debitDate= request.getPaymentTxn().getCrValDt();
Date now = new Date();
String response="";
SimpleDateFormat sdfDate = new SimpleDateFormat("dd/MM/yyyy");
String strCurrDate = sdfDate.format(now);
String strDebitDate = sdfDate.format(debitDate);
System.out.println("Current Date: " + strCurrDate);
Date currentDate = new SimpleDateFormat("dd/MM/yyyy").parse(strCurrDate);
Date txnDate = new SimpleDateFormat("dd/MM/yyyy").parse(strDebitDate);
System.out.println("C -> "+currentDate);
System.out.println("C -> "+txnDate);
if (txnDate!=null){
if (currentDate.equals(txnDate))
{
System.out.println("Valid Txn");
response="valid";
}
if (currentDate.after(txnDate))
{
System.out.println("--> Not Valid TXN Past");
response="notValid";
}
if (currentDate.before(txnDate)){
System.out.println("Future Valid TXn");
response="future";
}
}
return response;
}
PLease Chk it out its working fine
My database column datatype is timestamp. How do I insert the current date and time using a PreparedStatement or Statement?
I have tried this:
java.util.Date date = new java.util.Date();
System.out.println("Current Date : " + dateFormat.format(date));
pstmt.setDate(9, new java.sql.Timestamp(date.getTime()));
But the value inserted in the table is 1328847536746. This not right, i am using sqlite
There is a separate Timestamp value class in java.sql.
pstmt.setTimeStamp(9, new java.sql.Timestamp(date.getTime()));
The javadoc explains:
public class Timestamp
extends Date
A thin wrapper around java.util.Date that allows the JDBC API to identify this as an SQL TIMESTAMP value.
Use setTimestamp().
pstmt.setTimestamp(9, Timestamp.valueOf("2002-03-13 11:10:15.01"));
This is the code I've used so far to get it done
Timestamp nextRunTimestamp = null;
if(endDate != null || !endDate.equalsIgnoreCase(""))
{
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
dateFormat.parse(endDate);
Calendar tempDate = dateFormat.getCalendar();
tempDate.set(Calendar.HOUR, nextRunTime.get(Calendar.HOUR));
tempDate.set(Calendar.MINUTE, nextRunTime.get(Calendar.MINUTE));
tempDate.set(Calendar.SECOND, nextRunTime.get(Calendar.SECOND));
tempDate.set(Calendar.MILLISECOND, nextRunTime.get(Calendar.MILLISECOND));
if(nextRunTime.before(tempDate) || nextRunTime.equals(tempDate))
{
nextRunTimestamp = new Timestamp(nextRunTime.getTimeInMillis());
}
}
else
{
nextRunTimestamp = new Timestamp(nextRunTime.getTimeInMillis());
}
statement.setTimestamp(2, nextRunTimestamp);
statement.setInt(3, result.getInt("id"));
statement.executeUpdate();
DateFormat df = new SimpleDateFormat(yyyy/MM/dd HH:mm:ss); // any Date format
System.out.println("Current Date : " + df.format(new Date()));
pstmt.setDate(9, to_timestamp(df.format(new Date()),'YYYY/MM/DD HH24:MI:SS'));
Here you can use TO_DATE('todayDate', 'YYYY/MM/DD HH24:MI:SS') or
TO_TIMESTAMP('todayDate', 'YYYY/MM/DD HH24:MI:SS')