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);
Related
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...");
}
This question already has answers here:
How to parse a date? [duplicate]
(5 answers)
Java string to date conversion
(17 answers)
Closed 5 years ago.
I'm having trouble formatting a custom String back to a Date object. What i have:
String customString = "October 14, 2015;
Date date = new Date();
SimpleDateFormat s = new SimpleDateFormat("MM-dd-yyyy");
try {
date = s.parse(customString);
} catch (ParseException e) {
e.printStackTrace();
}
I always get a unappeasable date exception. Any pointers of what i'm doing wrong is appreciated.
Your pattern must be: new SimpleDateFormat("MMM dd,yyyy");
For more informations about SimpleDateFormat see the javadoc
Read the docs, https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html.
The argument of the constructor should have the format of the date you want to input.
For instance, if you want the full month name should have "MMMMM".
Just make the following change and the program will work.
SimpleDateFormat s = new SimpleDateFormat("MMMMM dd, yyyy");
This question already has answers here:
Calculating the difference between two Java date instances
(45 answers)
Closed 7 years ago.
I'm trying to write a Java script that computes the time difference between the current date and the last updated time stored on our Parse backend. Can anyone help me spot the bug in my code? You'd think this isn't so bad, but I've looked on Stack Overflow for hours to no avail.
//Create a date formatter.
SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'.'LLL'Z'");
//Create a date object for today's date.
Date currentDate=new Date();
//Create a string for the date from parse.
String parseTime = singleClaim.getString("updatedAt");
//Create a string for the current date.
String currentTime=currentDate.toString();
//Initialize the date object for the updatedAt time on Parse.
Date parseDate = null;
//Initialize the date object for the current time.
Date FormattedCurrentDate = null;
try {
//Here, we convert the parseTime string into a date object and format it.
parseDate = formatter.parse(parseTime);
//Here, we convert the currentTime string into a date object and format it.
FormattedCurrentDate = formatter.parse(currentTime);
}
catch (Exception e) {
e.printStackTrace();
}
//Get the time difference from the current date versus the date on Parse.
long difference = FormattedCurrentDate.getTime()-parseDate.getTime();
The combination of these two lines is probably causing your issue:
String currentTime=currentDate.toString();
// ...
FormattedCurrentDate = formatter.parse(currentTime);
The currentTime variable does not contain a properly formatting string that can be comsumed by your formatter.
I also see no need to create such a string, you could just do it as follows:
long difference = currentDate.getTime() - parseDate.getTime();
If you absolutely insist on making a round trip from date to string and back, you would have to create your currentTime string as follows:
currentTime = formatter.format(currentDate);
You should not call toString() to convert Date to String. And why you convert currentTime to String and later parse it to a date? This makes no sence.
//Create a date formatter.
SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'.'LLL'Z'");
//Create a date object for today's date.
Date currentDate=new Date();
//Create a string for the date from parse.
String parseTime = singleClaim.getString("updatedAt");
//Create a string for the current date.
String currentTime=currentDate.toString();
//Initialize the date object for the updatedAt time on Parse.
Date parseDate = null;
try {
//Here, we convert the parseTime string into a date object and format it.
parseDate = formatter.parse(parseTime);
}
catch (Exception e) {
e.printStackTrace();
}
//Get the time difference from the current date versus the date on Parse.
long difference = currentDate.getTime()-parseDate.getTime();
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
This question already has answers here:
Convert a string to a GregorianCalendar
(2 answers)
Closed 9 years ago.
i have this code:
String start = startBox.getText();
String finish = finishBox.getText();
myprogram.addPeriod(start, finish)
addPeriod method has 2 GregorianCalendar as parameters, so how to convert the 2 string into GregorianCalendar?
I tried a couple of ways that i read on this site but they don't work with me
startBox and finishBox are 2 JTextField filled with date in this format: YYYY/MM/DD.
How about this, the steps are self-explanatory but you want to have a handle on an instance of SimpleDateFormat of the pattern in which you have your date.
Parse your Strings to get a Date instance and set your specific date to the respective Calendar instances.
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
String start = startBox.getText();
String finish = finishBox.getText();
GregorianCalendar cal1 = new GregorianCalendar();
cal1.setTime(format.parse(start));
GregorianCalendar cal2 = new GregorianCalendar();
cal1.setTime(format.parse(finish));
myprogram.addPeriod(cal1, cal2);
}
} catch (ParseException e) {
e.printStackTrace();
}