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");
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)
In my sql query I have date formating as :
to_char(crtd_ts,'YYYY-MM-DD HH24:MI:SS.FF') crtd
and my database column stores the value as 2018-4-24.8.1. 30. 404577000
What is the way of doing the same thing in Java?
I tried this way, but I am getting an error.
private String formatDate(String refCrtdTs) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MMM-dd HH24:mm:ss.ff");
String dateInString = refCrtdTs;
try {
Date date = sdf.parse(dateInString);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
I am trying to replace the above sql query with hibernate criteria. My hibernate entity for the column is defined as
#Column(name="REF_CRTD_TS",columnDefinition="timestamp")
private String refCrtdTs;
and the column type in Oracle is Timestamp.
So hibernate criteria returns me this value as String which I want to format now.
Try this,
yy-M-d H:m:s.F
And your database column stores the value should be "2018-4-24 8:1:30.114"
F is Day in year (example: Feb 1st => F = 32, 31 day in Jan + 1 day in Feb)
You have to match same patter as per your sql, just try the same pattern to get in Java
I think this will work, please comment if you required more info
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS aa");
I try to compare date stored in mysql table column with current date using java.
I want to check whether the date is more than 3 days from the date which is stored in database table, it shows the error...
This is my code:
public static void main(String[] args) {
Connection con=null;
ResultSet rs=null;
String url="jdbc:mysql://localhost:3306/EDUCATION_MANAGEMENT";
try
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date crrDate=new Date();
crrDate=sdf.parse(sdf.format(crrDate));
Date dbDate=new Date();
System.out.println("Current Date ::: "+crrDate);
String userid="root";
String password="admin";
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection(url,userid,password);
Statement stmt=con.createStatement();
String getDate="select t_create_date from student_account where stud_id=100";
rs=stmt.executeQuery(getDate);
if(rs.next())
{
dbDate=sdf.parse(rs.getString("t_create_date"));
System.out.println("Database Date ::: "+dbDate);
}
if(crrDate.compareTo(dbDate)>3)
{
System.out.println("Date is less than 3");
}
else
{
System.out.println("Date is Greater than 3");
}
}
catch(SQLException sqle)
{
System.out.println("Error occured ::: "+sqle);
}
catch(Exception e)
{
System.out.println("Error occured ::: "+e);
}
}
Please tell me the code....
Mysql has pretty good date functions, you could just run
select t_create_date < now() - interval 3 day as more_than_3_days_ago
from student_account
where stud_id=100
then just get the boolean value more_than_3_days_ago and thats your answer.
As far as I can see, Andreas' answer will serve your purpose. If you want to do it in java, you will have to extract the data as Date Object
rs.getDate("DATE_COLUMN") and do the comparison.
You will probably find Joda Time very useful for comparisons.
I have the below method in which date is coming as parameter that is in form of string and that parameter name is dateString as shown below and ultimately the date is converted and stored n form of java.sql.Date which is also return type of this method.
public static java.sql.Date getSimpleDate11(String dateString) {
if (dateString == null) {
return null;
}
java.util.Date date = null;
java.sql.Date sqlDate = null;
try {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
df.setLenient(false);
date = df.parse(dateString);
sqlDate = new java.sql.Date(date.getTime());
} catch (Exception pe) {
throw new RuntimeException(
"The date entered is invalid or has incorrect format"
+ dateString);
}
return sqlDate;
}
Question:
I found that value is coming in this format 2014-07-23 (YYYY-MM-dd) and I want the return date (java.sql..Date) to be in 23-07-14 (dd-MM-YY).
This generates the date format you want - just use String as the return type instead of java.sql.Date:
public static String getSimpleDate11(String dateString) {
if (dateString == null) {
return null;
}
DateFormat dfIn = new SimpleDateFormat("yyyy-MM-dd");
DateFormat dfOut = new SimpleDateFormat("dd-MM-yy");
try {
Date date = dfIn.parse(dateString);
return dfOut.format(date);
} catch (ParseException e) {
throw new RuntimeException(
"The date entered is invalid or has incorrect format"
+ dateString);
}
}
In case you need to convert the incoming "yyyy-MM-dd" String date to a java.sql.Date object you already did everything right in the code you posted in your question.
A java.sql.Date object, just like a java.util.Date, stores the date you give it internally in some format you, as a programmer, don't have to care about. You just have to know that the date is stored in the object and that you can get it out of the object whenever you need it. If you're interested in technical details you can google for it but, as I said, in your case this doesn't matter.
Whenever you need a java.util.Date object just use the one you get out of your original getSimpleDate11(...) function. Whenever you need a String representation of the date in a certain format, like "dd-MM-yy", take the java.util.Date and plug it into a DateFormat object initialized with the output format you want, just like I did in my first answer with DateFormat dfOut (the format(...) method of DateFormat can handle both, java.util.Date and java.sql.Date objects).
I realize this has been asked a lot. I did actually look. I've spent hours looking around and trying to figure this out. I'm supposed to be making a program that stores what amounts to a list of appointments in a database, with a description, date, start time, and end time. It has to take input from the user to add or cancel appointments, so as far as I know that means I need to convert a string to a date.
These are my imports:
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Time;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Scanner;
As you can see, no java.util.Date there. Here is the bit where I'm getting the error:
private static java.sql.Date getDay()
{
Scanner in = new Scanner(System.in);
String input;
Date apptDay = null;
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
java.sql.Date sqlDate;
System.out.println("\nPlease enter the date of the appointment, format: yyyy/mm/dd");
while(apptDay == null)
{
try
{
input = in.next();
apptDay = (Date) df.parse(input);
}
catch(ParseException e)
{
System.out.println("Please enter a valid date! Format is yyyy/mm/dd");
}
}
sqlDate = new Date(apptDay.getTime());
return sqlDate;
}
I've added java.sql.Dates to it and mucked about with it a bunch trying to get it to work, but it's still giving me this:
Exception in thread "main" java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Date
at Calendar.getDay(Calendar.java:47)
Any ideas on what I'm doing wrong or how to make this work would be very much appreciated.
Edit: I thought perhaps it would help if I added the bit of code that is calling this so maybe it will be more clear how I am trying to use it, so here is the addAppointment() method, so you can see where getDay() is being called and where it's going.
public static void addAppointment() throws SQLException
{
//get the info
String desc = getDesc();
java.sql.Date apptDay = getDay();
Time[] times = getTime();
Time startTime = times[0];
Time endTime = times[1];
int key;
Connection conn = SimpleDataSource.getConnection(); //connect to the database
try
{
PreparedStatement max = conn.prepareStatement("SELECT MAX(ID) FROM Calendar");
ResultSet result = max.executeQuery();
key = result.getInt("ID") + 1;
PreparedStatement stat = conn.prepareStatement(
"INSERT INTO Calendar " +
"VALUES (?, ?, ?, ?, ?)");
stat.setInt(1, key);
stat.setString(2, desc);
stat.setDate(3, apptDay);
stat.setTime(4, startTime);
stat.setTime(5, endTime);
stat.execute();
System.out.println("\nAppointment added!\n");
}
finally
{
conn.close(); //finished with the database
}
}
It would be much simpler to change the input format to yyyy-MM-dd and use java.sql.Date.valueOf(String date) method which converts a string in the above format to a java.sql.Date value directly.
This should work:
private static java.sql.Date getDay()
{
Scanner in = new Scanner(System.in);
String input;
Date apptDay = null;
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
java.sql.Date sqlDate;
System.out.println("\nPlease enter the date of the appointment, format: yyyy/mm/dd");
while(apptDay == null)
{
try
{
input = in.next();
apptDay = (Date) df.parse(input);
}
catch(ParseException e)
{
System.out.println("Please enter a valid date! Format is yyyy/mm/dd");
}
}
sqlDate = new java.sql.Date(apptDay.getTime());
return sqlDate;
}
java.sql.Date and java.util.Date are two different Classes. You need to convert the sql date into util date which is compatible with Calendar.
Date jDate = new Date(sqlDate.getTime());
and vice-versa
java.sql.Date sqlDate = new java.sql.Date(jDate.getTime());
The following statement caused the error:
apptDay = (java.sql.Date) df.parse(input);
In fact, the type of the return value of java.text.DateFormat.parse(String) is java.util.Date, which is incomparable with java.sql.Date.
In your situation, the easiest way might be using java.util.Date instead of java.sql.Date.
Another note: your class name Calendar is duplicate with java.util.Calendar. And it is not a good coding style to use class names which are already used by the standard library.
sqlDate = new java.sql.Date(apptDay.getTime());
Date.valueOf(scanner.nextLine())
String strDate = scanner.nextLine();
SimpleDateFormat format= new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date = format.parse(strDate);
Try below method -
private static java.sql.Date getDay() throws SQLException {
Scanner in = new Scanner(System.in);
String input;
java.util.Date utilDay = null;
DateFormat df = new SimpleDateFormat("yyyy-mm-dd");
System.out.println("\nPlease enter the date of the appointment, format: yyyy-mm-dd");
while(utilDay == null){
try{
input = in.next();
utilDay = (java.util.Date) df.parse(input);
}catch(ParseException e){
System.out.println("Please enter a valid date! Format is yyyy/mm/dd");
}
}
java.sql.Date sqlDate = new java.sql.Date(utilDay.getTime());
return sqlDate;
}
And from main() method, call this method -
Date birthday = getDay();
java.time
It’s time someone writes the modern answer to this question.
Assuming that you are using (or can start using) a JDBC 4.2 compliant driver you should not use the two Date classes nor DateFormat or SimpleDateFormat. All those classes are poorly designed, the last two particularly troublesome. They are also long outdated. Instead rely on java.time, the modern Java date and time API. It’s much nicer to work with. We need a LocalDate and a DateTimeFormatter.
Now we’re at it, don’t use java.sql.Time either. Use LocalTime from java.time.
So your variable declarations become:
//get the info
String desc = getDesc();
LocalDate apptDay = getDay();
LocalTime[] times = getTime();
LocalTime startTime = times[0];
LocalTime endTime = times[1];
int key;
Only for passing the java.time objects to your prepared statement you don’t use setDate and setTime. You need to use setObject:
stat.setInt(1, key);
stat.setString(2, desc);
stat.setObject(3, apptDay);
stat.setObject(4, startTime);
stat.setObject(5, endTime);
stat.execute();
Everything else is as before. For parsing the user input string to a LocalDate, here is a short demonstration:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy/M/d");
String input = "2019/11/09";
try {
LocalDate aptDate = LocalDate.parse(input, dateFormatter);
System.out.println("Parsed date: " + aptDate);
} catch (DateTimeParseException dtpe) {
System.out.println("Please enter a valid date. Format is yyyy/mm/dd");
}
The output from the last snippet is:
Parsed date: 2019-11-09
I have specified just one M and one d in the format pattern string to allow the user to enter one or two digits for month and day of month, for example 2019/11/9. Most users I know will appreciate this.
Link
Oracle tutorial: Date Time explaining how to use java.time.