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.
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)
I insert the current date in a table. I have a method to get the current datet:
private static java.sql.Date getCurrentDate() {
java.util.Date today = new java.util.Date();
return new java.sql.Date(today.getTime());
}
Or in some cases I get the date from a from in a String format e.g. 2016-10-12 and then I call this method with action.setTodayInfo(session, getCurrentDate()); to insert to a table the date and some Boolean variables
public void setTodayInfo(HttpSession session, Date date)
throws SQLException, ClassNotFoundException {
System.out.println("Initialize today's info...");
String sq = "INSERT INTO IsSELECTED (date, morning, noon, night) VALUES (?, ?, ?, ?)";
try {
Class.forName(typeDB);
c = DriverManager.getConnection(path);
stm = c.prepareStatement(sq);
PreparedStatement stm = c.prepareStatement(sq);
stm.setDate(1, date);
stm.setBoolean(2, FALSE);
stm.setBoolean(3, FALSE);
stm.setBoolean(4, FALSE);
int rowsAffected = stm.executeUpdate();
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (stm != null) {
stm.close();
}
if (c != null) {
c.close();
}
}
}
when I look in the table the date field has this 1434473268231 and not the current day in format like 2015/06/16.. The table format is:
CREATE TABLE "IsSELECTED"(
"date" DATETIME PRIMARY KEY NOT NULL DEFAULT (CURRENT_DATE) ,
"morning" BOOL NOT NULL DEFAULT (0) ,
"noon" BOOL NOT NULL DEFAULT (0) ,
"night" BOOL NOT NULL DEFAULT (0)
)
There is no need to worry about the format of the date when storing it. The database will simply store the date instance and you can use one of its functions to format it on retrieval.
You could also use Java to format the date on retrieval using SimpleDateFormat
Divide 1434473268231 by 24*60*60*1000*365 and you'll get 45, which is the number of the years since the start of the epoch 1970.
This means that the value you are seeing is the number of milliseconds since Jan 1, 1970.
That should be OK - usually date values are internally stored as milliseconds since some agreed-upon point in time.
According to this: https://www.sqlite.org/datatype3.html SQLLite doesn't really have a special type for DATETIME.
"Applications can chose to store dates and times in any of these formats and freely convert between formats using the built-in date and time functions."
I am trying to insert a value in the postgres table through Java . Column type is timestamp.
The code is like this :
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
String gameStartedTime = format.format(new Date());
String query= "UPDATE gameStatus g SET g.status ='" + gameStatus
+ g.gameStartTime= to_date('"
+ gameStartedTime + "','yyyy-MM-dd HH:mm:ss')"
// Doesn't matter much
+ " WHERE g.status = 'STARTED' AND " + "g.condition="+ game.getCondition();
Now when I try to execute this statement it fails I get the message like this :
ERROR: conflicting values for "mm" field in formatting string.
DETAIL: This value contradicts a previous setting for the same field type.
I am not sure what is going wrong !!
Any help on this will be useful.
Thanks in advance.
-JE
mm is always the month for the to_date() function. There is no difference between mm and MM (unlike in Java's SimpleDateFormat).
You need to use mi for the minutes.
A full list of all patterns is available in the manual: http://www.postgresql.org/docs/current/static/functions-formatting.html#FUNCTIONS-FORMATTING-DATETIME-TABLE
But you shouldn't use "dynamic" SQL in the first place. It's better to use a PreparedStatement, java.sql.Timestamp and setTimestamp() instead. That relief you from any formatting problems and protect you against SQL injection.
do like this.
java.sql.Date date=new Date();
Timestamp timestamp = new Timestamp(date.getTime());
this.date = timestamp;
Then add this.date into database..
try it:
ps.setTimestamp(position, new Timestamp(System.currentTimeMillis()));
Try to split the date part from the query and try to compare these values.
It appears (at least from where I see) that the mm which stand for minutes,
does not comply with g.gameStartTime= to_date.
If you pull this part outside the query you can check the values, maybe you will find what the problem is there.
This way works for me using current time:
String query = "INSERT INTO table1 (id,t) VALUES (?, ?)";
//update table1 set t=? where id=?
Connection con = null;
PreparedStatement ps = null;
try{
con = dataSource.getConnection();
ps = con.prepareStatement(query);
ps.setLong(1, 1234); // update ps.setLong(2, 1234);
Calendar cal = Calendar.getInstance();
Timestamp timestamp = new Timestamp(cal.getTimeInMillis());
ps.setTimestamp(2,timestamp); // ps.setTimestamp(1,timestamp);
int out = ps.executeUpdate();
if(out !=0){
System.out.println("Record saved");
}
}catch(SQLException e){
e.printStackTrace();
}finally{
try {
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
Or, you can establish a specific timestamp by using these lines:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2015);
cal.set(Calendar.MONTH, 0); // 0 january
cal.set(Calendar.DAY_OF_MONTH, 26);
cal.set(Calendar.HOUR_OF_DAY, 10);
cal.set(Calendar.MINUTE, 47);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Timestamp timestamp = new Timestamp(cal.getTimeInMillis());
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");
I want to change date format yyyy-mm-dd hh:mm:ss.SSS ( which is stored in database in string format) to mm/dd/yyyy for their comparison
while(rs.next())
{
reportBean bean=new reportBean();
String proj_close_date=rs.getString(3);
String added_on=rs.getString(4);
DateFormat myDateFormat = new SimpleDateFormat("MM/dd/yyyy");
DateFormat myDateFormat1= new SimpleDateFormat("yyyy-mm-dd hh:mm:ss.SSSSSS");
Date myDate1 = null;
Date myDate2 = null;
Date myDate3 = null;
Date myDate4 = null;
Date myDate5 = null;
try
{
if(proj_close_date==null || proj_close_date.trim().equals(""))
{
System.out.println("\n ****** In IF Loop ");
bean.setCust_code(rs.getString("customer_code"));
bean.setProject_code(rs.getString("project_code"));
list.add(bean);
}
else
{
System.out.println("\n ****** In Else Loop ");
myDate1 = myDateFormat.parse(proj_close_date);
myDate2 = myDateFormat.parse(frm_date);
myDate3 = myDateFormat.parse(to_date);
myDate5 = myDateFormat1.parse(added_on);
myDate4 = myDateFormat.format(myDate5);
System.out.println("Project Code ---->"+rs.getString(2));
System.out.println("Proj_close_date ------>"+myDate1);
System.out.println("From Date ---->"+myDate2);
System.out.println("to Date ---->"+myDate3);
System.out.println("Added_on --->"+myDate4);
System.out.println("Added_on 1 ie Date 5 ---->"+myDate5);
if(myDate1.after(myDate2) && myDate1.before(myDate3)) // means --> if(proj_close_date.after(frm_date) && proj_close_date.before(to_date))
{
if(myDate1.after(myDate4)) // means --> if(proj_close_date.after(added_on))
{
bean.setCust_code(rs.getString("customer_code"));
bean.setProject_code(rs.getString("project_code"));
list.add(bean);
}
else
{
bean.setCust_code(rs.getString("customer_code"));
bean.setProject_code(rs.getString("project_code"));
list.add(bean);
}
}//if
}//else
}//try
catch (ParseException e)
{
System.out.println("Invalid Date Parser Exception ");
e.printStackTrace();
}
}
rs.close();
stmt.close();
}
catch(SQLException sex)
{
sex.printStackTrace();
}
finally
{
closeConnection();
}
You have set myDateFormat1 to "yyyy-mm-dd hh:mm:ss.SSSSSS". I think the first mm should be in uppercase.
I recommend you check your format strings with the documentation if SimpleDateFormat.
A few notes
convention is for Java class names to have each noun capitalised, reportBean becomes ReportBean
don't refer to SQL columns by position, always use a name instead rs.getString("customer_code") rather than rs.getString(3)
use meaningful variable names, myDate1 becomes closeDate
practice debugging your code so you can eliminate System.out.println()
gracefully release resources, stmt.close() moves within a finally block
use a logging framework, rather than swallowing Exception, e.g. log.error("Invalid Date Parser Exception", e);
Some specific pointers:
new SimpleDateFormat("yyyy-mm-dd hh:mm:ss.SSSSSS") // as already noted, mm is the format for minute, MM is the format for month
myDate4 = myDateFormat.format(myDate5); // invalid as you are asigning a String to a Date
if(myDate1.after(myDate4)) // irrelevant as both if & else block execute the same code
rs.close() // not necessary as closed when `Statement` is closed
see Javadoc
Are you sure that your database schema is all varchar columns? I'd recommend that you fixed that if its the case. Otherwise you can call rs.getDate() instead.