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)
Related
I am creating an appointment app that has the capability to view monthly/weekly. The standard view, is able to show correct times in HH:mm, only between 9:00 - 17:00 . However, the monthly/weekly I can't convert and shows in full 24 hour time.
For the monthly I have:
public LocalTime getTime() {
return time;
}
#FXML
private void viewByMonthHandler(ActionEvent event) {
DataProvider.getAppointmentsByMonth().clear();
DataProvider.getAppointmentsByWeek().clear();
if(viewByMonthRadioButton.isSelected()) {
// I was using these two to try and convert
//DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
//DateTimeFormatter timeFormat = DateTimeFormatter.ofPattern("MMMM HH:mm");
Calendar cal = Calendar.getInstance();
String month = new SimpleDateFormat("MMMM").format(cal.getTime());
DataProvider.setMonthlyView(month);
}
sortAppointment();
viewByComboBox.setItems(viewByMonth);
}
I have tried :
String month = new DateTimeFormatter.ofPattern("MMMM HH:mm").format(cal.getTime());
and:
String month = new SimpleDateFormat("MMMM").format(timeFormat);
error:
Caused by: java.lang.IllegalArgumentException: Cannot format given Object as a Date
for the weekly I have:
#FXML
private void viewByWeekHandler(ActionEvent event) {
DataProvider.getAppointmentsByMonth().clear();
DataProvider.getAppointmentsByWeek().clear();
if(viewByWeekRadioButton.isSelected()) {
DataProvider.setWeeklyView(0);
}
sortAppointment();
viewByComboBox.setItems(viewByWeek);
}
setWeeklyView:
public static void setWeeklyView (int weekForReference) {
try {
ArrayList<Integer> selectedAppointmentsByWeek = new ArrayList<>();
Statement statement = DBConnection.getConnection().createStatement();
ResultSet weeklyAppointments = statement.executeQuery("SELECT appointmentId from appointment where year(start) = YEAR(date_add(curdate(), interval " + weekForReference + " WEEK)) and weekofyear(start) = weekofyear(date_add(curdate(),interval " + weekForReference + " WEEK));");
while(weeklyAppointments.next()) {
selectedAppointmentsByWeek.add(weeklyAppointments.getInt(1));
}
for(int appointmentId : selectedAppointmentsByWeek) {
ResultSet selectAppointment = statement.executeQuery("SELECT customer.customerName, customer.customerId, contact, title, type, location, description, start, end FROM appointment JOIN customer ON customer.customerId = appointment.customerId WHERE appointmentId =" + appointmentId);
selectAppointment.next();
Appointment appointment = new Appointment();
String customerName = selectAppointment.getString(1);
int customerId = selectAppointment.getInt(2);
String contact = selectAppointment.getString(3);
String title = selectAppointment.getString(4);
String type = selectAppointment.getString(5);
String location = selectAppointment.getString(6);
String description = selectAppointment.getString(7);
String start = selectAppointment.getString(8);
String end = selectAppointment.getString(9);
appointment.setCustomerName(customerName);
appointment.setContact(contact);
appointment.setTitle(title);
appointment.setType(type);
appointment.setLocation(location);
appointment.setDescription(description);
appointment.setStart(start);
appointment.setEnd(end);
appointmentsByWeek.add(appointment);
}
}
catch(SQLException ex) {
System.out.println("Error " + ex.getMessage());
}
}
The setMonthlyView is almost identical, just replacing weekly with monthly. How could I go about formatting these so they are no longer HH:mm:ss.S and in between 9:00-17:00? I have taken the advice previously given to me for the little parts, and still can't figure it out. Thank you so much for taking the time to read and help.
Do one of these do what you want.
12 hour
String localDateTime12Hour =
LocalDateTime.now().format(DateTimeFormatter.ofPattern("MMMM hh:mm a"));
System.out.println(localDateTime12Hour);
24 hour
String localDateTime24Hour =
LocalDateTime.now().format(DateTimeFormatter.ofPattern("MMMM HH:mm"));
System.out.println(localDateTime24Hour);
Prints
July 06:11 PM
July 18:11
Use HH for 24 hour
Use hh for 12 hour (the a provides AM or PM)
Remember to use LocalDateTime and not LocalTime when specifying formatter attributes like MMMM. You are returning a LocalTime object in your getTime() method. And I would avoid using Calendar and Date as they are outmoded. Use classes from the java.time package.
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).
I am trying to get client arrival date and compare it with my SQL database to see if in my data base the same date exists. however i receive the following error: The operator > is undefined for the argument type(s) java.lang.String, java.lang.String
P.S I need to compare it via java not using sql query
public void makeNewReservation() throws ParseException {
// Enter informations
System.out.println("Date of arrivel?");
Scanner in = new Scanner(System.in);
String date_entree = in.next();
System.out.println("Date of exit? dd/MM/yyyy");
String date_sortiee = in.next();
calculateDaysDifference(date_sortiee, date_entree);
public void calculateDaysDifference(String date_entree, String date_sortiee) throws ParseException{
ConnectionMySQL myConnection=new ConnectionMySQL();
Connection conSQL=myConnection.startDBConnection();
boolean connectionOK=myConnection.checkConnection(conSQL);
String query = ("SELECT `START_DATE`,`END_DATE` FROM `room_booking");
//if everything is fine with the connection, i try to execute a query
if (connectionOK){
try{
ResultSet mesResultats=myConnection.executeQuery(conSQL, query);
//the while loop is just for me to check the dates
while (mesResultats.next()) {
System.out.println("START_DATE: "+mesResultats.getString(1)+" END_DATE : "+ mesResultats.getString(2));
if (date_entree > mesResultats.getString(1){
System.out.println("cant reserve room room reserved already");
}
}
// je ferme la connexion
conSQL.close();
}
catch(SQLException e){
e.printStackTrace();
}
}
my data base
You need to compare 2 Dates
1) Convert the input String into Date
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
java.util.Date d=df.format(/*date String*/);
NOTE: df.format will throw parseException if the String format does not match "yyyy-MM-dd" . I leave it upto you to make sure the date string is of the specified format.
2)get Date from sql query
java.util.Date sqlDate=new java.util.Date(resultset.getDate().getTime());
NOTE : resultset.getDate() will give you java.sql.Date class's object.
3) Compare 2 dates
try this logic
Date date1=new Date(df.parse(mesResultats.getString(1)));
Date date2=new Date(df.parse(mesResultats.getString(2)));
int status=date1.compareTo(date2); //compareto is a function defined for date
if status==0 print same date
if status<0 print date1 is older then date2
if status>0 print date1 is newer then date2
[Update after comment]
DateFormat df = new SimpleDateFormat("Format of your date goes here");
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