Compare date from database with current date - Java [duplicate] - java

This question already has answers here:
Dates with no time or timezone component in Java/MySQL
(6 answers)
How do I check if a date is within a certain range?
(17 answers)
How to convert epoch to mySQL timestamp in JAVA
(2 answers)
Closed 1 year ago.
I have a problem with types of date variables... I need to take date from database and compare it with current date... I think that I get date from database in right way, but I don't know how to take current date in same type of date variable to can compare it.. In my database format for saving data of date is "DATE" yyyy-mm-dd.
Date now = new Date();
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/database", "root", "");
Statement stmt = con.createStatement();
String sql="SELECT * FROM users WHERE username='"+textField_Username.getText()+"' AND password='"+textField_Password.getText().toString()+"'";
ResultSet rs=stmt.executeQuery(sql);
if(rs.next()) {
Date expire = new Date(rs.getDate("account_expire").getTime());
if(expire.before(now)){
}
dispose();
JOptionPane.showMessageDialog(null, "Login Sucessfully.");
Workshop window = new Workshop();
window.frmCfWorkshop.setVisible(true);
} else {
JOptionPane.showMessageDialog(null, "Incorrect username and password...");
}

Related

How to insert datetime field in mySql database using PreparedStatement in java? [duplicate]

This question already has answers here:
How to store Java Date to Mysql datetime with JPA
(13 answers)
Closed 6 years ago.
I red here about similar questions, but I didnt find solution for my problem, how to insert datetime field in mySql database using PreparedStatement in java? I didnt find anything related to this question and PreparedStatement.
So, I have this code:
public void sacuvajDezurstva(List<Dezurstvo> listaDezurstava) throws SQLException {
String sqlSacuvajDezurstva = "INSERT INTO dezurstvo (Datum,IspitniRokID, NastavnikID, PredmetID) VALUES (?,?,?,?)";
PreparedStatement ps = konekcija.prepareStatement(sqlSacuvajDezurstva);
for (Dezurstvo dezurstvo : listaDezurstava) {
ps.setDate(1, new Date(dezurstvo.getDatum().getTime()));
ps.setLong(2, dezurstvo.getIspitniRok().getIspitniRokID());
ps.setLong(3, dezurstvo.getNastavnik().getNastavnikId());
ps.setLong(4, dezurstvo.getPredmet().getPredmetID());
ps.executeUpdate();
}
konekcija.commit();
}
This code works, but the first ps parametar here which is Date is problem, because in database only part of this attribute - Date is saved, precisely day, month and year are saved when I use this method. But hour, minutes and seconds are only 00:00:00. So whole date in database looks like this:
2016-06-26 00:00:00
This column in my datatable where I insert Date is datetime type. And when I do debug, I see that this - dezurstvo.getDatum().getTime()) has the normal value of date inserted through the form. So it has, day, month, year, hour, minutes and seconds, but this ps.setDate, acctualy ps, has only the value of day, month and year.
I presume the problem is in SQL query but I don`t know how to do this when I have only ? in VALUES and not some actual date.
Thanks for help!
You need to format your date. Try the following
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;
String currentDateTime = format.format(date);
Then use setString in your prepared statement.
To insert a Date into a DATETIME field it should be formatted like "yyyy-MM-dd HH:mm:ss".
Another option is to use a TIMESTAMP field instead.

Convert util.date to sql.date with date and time in java [duplicate]

This question already has answers here:
java.util.Date to java.sql.Date doesn't contain Time
(4 answers)
Closed 6 years ago.
I am trying to convert java.util.Date into java.sql.Date with below function but this function is giving the time a s 00:00:00.000.
private java.sql.Date getCurrentDate() {
java.util.Date today = new java.util.Date();
return new java.sql.Date(today.getTime());
}
please help me how can I get both date and time in java.sql.date.
thanks
Converting java.util.Date to java.sql.Date will lost the hour,minute and second.
So if it is possible, I suggest you use java.sql.Timestamp.
final String str = "INSERT INTO table (curTime) VALUES( ?)";
final PreparedStatement preparedStatement =connection.prepareStatement(str);
preparedStatement.setTimestamp(1, new Timestamp(date.getTime()));
you have to use a timestamp for that its not possible with java.sql.date since it removes data related to your time.

Error Timestamp format [duplicate]

This question already has answers here:
Sql timestamp to Java date?
(2 answers)
Closed 8 years ago.
I'm trying to retrieve a Timestamp from my DB and I need to convert it to a java.util.Date
I've been following several examples I've found in stackoverflow but I keep getting the following exception:
java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]
I don't know why, I've tried several ways of doing this, can you help me?
Here's my code:
//select all partitions from table "LDRS"
stmtSelect = connection.prepareCall("Select HIGH_VALUE from user_tab_partitions where table_name = 'LDRS'");
ResultSet rs = stmtSelect.executeQuery();
SimpleDateFormat myFormat = new SimpleDateFormat("dd.MM.yyyy");
while (rs.next()) {
try {
Timestamp ts = rs.getTimestamp("HIGH_VALUE");
Date date1 = myFormat.parse(ts.toString());
Date date2 = myFormat.parse(""+new Date());
// compares the current date with the partition date, if the difference between them is more than 30 days
// drops the partition
long diff = date2.getTime() - date1.getTime();
...
}
Stop converting the values to strings and back. A java.sql.Timestamp already is a java.util.Date:
long now = System.currentTimeMillis();
while (rs.next()) {
Timestamp ts = rs.getTimestamp("HIGH_VALUE");
long diff = ts.getTime() - now;
... use diff ...
}
You should only be dealing with strings when you fundamentally want to do so. In this case, "finding the difference between a stored timestamp and the current time" has nothing to do with a string representation.

How do I pass a Date as SQL parameter in Java without losing the time part? [duplicate]

This question already has answers here:
Converting ISO 8601-compliant String to java.util.Date
(31 answers)
Closed 8 years ago.
For example, I have this String: 06/10/2013 18:29:09. I want to convert this string and put it in a SQL database (as Date).
How can I convert this to an sql date, so that it could be inserted into a database? I want the hours minutes and seconds to remain as well.
I tried the following:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date javaDate = sdf.parse("06/10/2013 18:29:09");
java.sql.Date date = new java.sql.Date(javaDate.getTime());
The problem is here:
java.sql.Date date = new java.sql.Date(javaDate.getTime());
java.sql.Date stores the date part of your timestamp. If you want/need to handle both date and time, use java.sql.Timestamp instead:
java.sql.Timestamp date = new java.sql.Timestamp (javaDate.getTime());
More info:
Date vs TimeStamp vs calendar?
You will use a SimpleDateFormat object to parse the string to java.util.date and then use the getTime() method to instantiate a java.sql.Date.
String input = "06/10/2013 18:29:09";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
java.util.Date dt = sdf.parse(input);
java.sql.Date dtSql = new java.sql.Date(dt.getTime());
If you are working with String type for date input and then you want to save that in a database like MySQL, you should use an appropriate Date Format for it. There's a class called "SimpleDateFormat" which you can use for that purpose. You can find a sample in the following link, also a brief explanation on how it works. Hope it helps.
Example: http://www.java2s.com/Tutorial/Java/0040__Data-Type/SimpleDateFormat.htm
Best Regards.
Here's a simple demo. In a Database table like this.
You can insert into it like this.
//the SQL statement for creating the database table
create table user(id, integer primary key, username varchar(100), date_created varchar(100));
//the java code to insert into the table created above.
try{
String date = new SimpleDateFormat("dd/MM/YYYY HH:mm:ss").format(new Date());
String sql = "insert into user(username, date_created) values('olupotd', '"+date+"')";
int done = statement.executeUpdate(sql);
if(done > 0)
//inserted
else
//not inserted.
}catch(java.sql.SQLException e){}
Hope that helps

Comparing java.util.date to java.sql.date unsucessfully [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I am writing this section of code to compare a query to the database with the current date in order to tell if a student is already checked into class. I can cast them both to string and they look identical but they are different in some way at a byte level and the if statement is still returning false. What can be done?
Also this does not work.
java.sql.Date date = new Date();
It gives an error that is why I tried changing the format to .sql.Date with the first 2 lines. It did not help but I left it in there to show what I have tried.
here is the code
public boolean checkTodaysAttendance(int ID){
//date stuff
java.util.Date date = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
//System.out.println(sqlDate);
boolean attend = false;
try {
PreparedStatement statement = con.prepareStatement("SELECT Date FROM attendance WHERE ID="+ID);
rs1 = statement.executeQuery();
while(rs1.next()) {
//System.out.println(rs1.getDate("Date"));
if (rs1.getDate("Date").toString().trim(). == sqlDate.toString().trim()) { //my problem is on this line
attend = true; //string don't equal at a byte level
}
}
}catch(Exception ex){
System.out.println(ex);
}
//System.out.println(attend);
return attend;
}
Change both dates to strings using simple date format and then compare.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss");
// create a new String using the date format we want
String dateString= formatter.format(date);

Categories