Handling Dates in Java - java

I am new to java GUI
I have a form for simple data input that saved to mySQL. Among the textboxes I have defined is dateOfBirth.
In mySQL, the dateOfBirth column is type DATE.
When I attempt to save my record, I get incompatible conversions. How Do I handle this? The Date fields are DOR and DOB.
I tried to define a format :
DateFormat df= new SimpleDateFormat("dd/MM/yyyy");
and also changed redefined the var DOR or DOB as String:
String DOB = new String();
then when inserting into database, formatted the var like this:
df.format(DOB)
I still got the error: "Error: Cannot format given object as a Date". What to do?
String query = "INSERT INTO members (MemberID,FamilyName,BaptismName,DateOfRegistration,DateOfBirth,FatherName,MotherName,gender,MemberType,Address,Residence,City,CreatedBy)"
+"VALUES('"+memberID+"','"+familyName+"','"+baptismName+"','"+DOR+"','"+DOB+"','"+fatherName+"','"+motherName+"','"+gender+"','"+memberType+"','"+address+"','"+residence+"','"+city+"','"+operator+"')";
con.UpDate(query);

First of all i would not use that query for the insert. You should use a prepared statement. It's safer against sql injection.
PreparedStatement ps =
connection.prepareStatement("INSERT INTO members (MemberID,FamilyName,BaptismName,DateOfRegistration,DateOfBirth,FatherName,MotherName,gender,MemberType,Address,Residence,City,CreatedBy) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)");
ps.setString(1, memberID); //or the correct type if not String
ps.setString(2, familyName);
ps.setString(3,baptismName);
DateFormat df= new SimpleDateFormat("dd/MM/yyyy"); //this the the format in which the user enters the date in the textbox. they have to input a string like 12/31/2014
java.util.Date date=df.parse(DOB); //DateFormat class has a method called parse which returns a java.util.Date object
ps.setDate(4, new java.sql.Date(date.getTime()));
//PreparedStatement class method setDate takes 2 parameters
//first is the index of the parameter in the prepared statement, and the second
//is java.sql.Date object.
//use constructor of java.sql.Date which takes a long parameter to create this object
//java.util.Date getTime() method returns a long value representing the date object
//so basically you convert string DOB to java.Util.Date,
//then convert java.Util.Date object to java.sql.Date needed by prepared statement
...
ps.executeUpdate();

Related

Convert String to "yyy-MM-dd" format with Date as data type

I'm trying to get the data stored in database by getting the date then populate the table.
List<String> contents = new ArrayList<>();
List<Record> records
try {
Session session = sessionFactory.getCurrentSession();
Query<World> query = null;
query = session.createQuery("from World where date like :dateCont, World.class);
query.setParameter("dateCont", "%" + contents.get(0) + "%");
worlds = query.getResultList();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The problem here is that it gives me an error exception:
java.lang.ClassCastException: class java.lang.String cannot be cast to
class java.util.Date (java.lang.String and java.util.Date are in
module java.base of loader 'bootstrap')
I know what's wrong because the List<String> contents values are string and needed to be converted to Date but I tried so many codes and it doesn't work.
//The following are the codes that I tried but it won't work:
//FIRST
Date date = new SimpleDateFormat("MM/dd/yyyy").parse(contentsStart.get(0));
new SimpleDateFormat("yyyy-MM-dd").format(date);
//---------------------------------------
//SECOND
Date newDate;
DateFormat formatter = null;
formatter = new SimpleDateFormat("yyyy-MM-dd");
newDate = (Date) formatter.parse(contentsStart.get(0));
So, is there any way to change the given value to date but it should retains the format "yyyy-MM-dd" and the datatype should be Date.
PS: the format of date in database is "yyyy-MM-dd" also.
Both my date entity field and date from DB is both Date as their
datatype.
Try this:
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date d1= (Date) format.parse(yourDate);
You can use like operator only on string (VARCHAR) fields. In the WHERE clause you have to convert your field to string (using format function) in order to be able to use LIKE. So you have to call the convert function (also) IN THE QUERY.
Unfortunately, there are no DATE-functions in EJBQL, so you will have to switch to the native query. For example, for Oracle you can use TO_CHAR like this
SELECT ... WHERE TO_CHAR(date, 'MM/DD/YYYY') LIKE ...
For good performance you will have to add a functional index.
See also http://www.sqlines.com/oracle-to-sql-server/to_char_datetime
One alternative would be to add a new string column date_string, that will contain the formatted representation of your date and use this column with LIKE. But you will have to make absolutely sure, that both dates are always synchronized.

How to get Date from a resultSet

I have a problem when getting a Date object from a ResultSet. In database it has a value (for example 2014-08-01) and after getting it from resultSet, it has another value (2014-08-31). I know that ResultSet's getDate method returns java.sql.Date, but I tried a few solutions, such as:
Date date=new java.util.Date(resultSet.getDate(3).getTime());
or
Date date=resultSet.getTimestamp();
but the problem was the same.
If I try
Date date=resultSet.getDate();
It throws a NullPointerException.
Can anybody explain this?
In your case you were not providing the columnName of the Date field to be retrieved.
This should do the job
while (rs.next()) {
java.sql.Time dbSqlTime = rs.getTime("columnName");
java.sql.Date dbSqlDate = rs.getDate("columnName");
java.sql.Timestamp dbSqlTimestamp = rs.getTimestamp("columnName");
java.util.Date dbSqlTimeConverted = new java.util.Date(dbSqlTime.getTime());
java.util.Date dbSqlDateConverted = new java.util.Date(dbSqlDate.getTime());
System.out.println(dbSqlTimeConverted);
System.out.println(dbSqlDateConverted);
}
iterate over the ResultSetObject get the Date from the ResultSetObject which is java.sql.Date then convert it to java.util.Date
You should use the java.sql.Date instead of java.util.Date, because ResultSet.getDate() returns an SQL Date, and not a Java one.

how to insert data type date(yyyy-MM-dd) in sqlite database and retrive data between two dates in android

I have a Sqlite3 database table contains name,address,date of birth details.i want to display 1990-01-01 to 1995-01-01 details.
but Sqlite3 database stores only following data types.
TEXT
NUMERIC
INTEGER
REAL
NONE
Any one have some hint to store and retrieve date format data..?
From my own experience on doing several projects with database in Android my answer is:
Do not store the date as a string. Never! Ever! Store them as Unix timestamps and format them as needed during runtime.
the important thing here is to separate what is your data and what is the on-screen representation of your data. Storing in a database the on-screen representation of your data is wrong.
You'll always store your dates as INTEGER types.
So for example to store the date now you'll store the value System.currentTimeInMilis
To select between 1990-01-01 and 1995-01-01 you will:
long val1 = new GregorianCalendar(1990, 01, 01).getTimeInMillis();
long val2 = new GregorianCalendar(1995, 01, 01).getTimeInMillis();
and then you'll do the normal SELECT statement between those 2 values.
to show those values in the screen as yyyy-MM-dd you'll use the SimpleDateFormat class:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
long longDate = cursor.getLong(colNumber); // from the database
String stringDate = dateFormat.format(new Date(longDate));
Use this code to convert your date into millisecond format and store it into your database as INTEGER types
String someDate = "1995-01-01";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(someDate);
System.out.println(date.getTime());
date.getTime()-give the millisecond format
At the same way to convert your input (i.e from 1990-01-01 and to date 1995-01-01)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = sdf.parse(1990-01-01);
value1=date.getTime();
Date date2 = sdf.parse(1995-01-01);
value2=date.getTime();
Retrieve from database using following query
db.rawQuery("SELECT * FROM table_name WHERE column_name BETWEEN "+value1+" AND "+value2+"",null);
or
db.rawQuery("SELECT * FROM table_name WHERE column_name<="+value1+" AND column_name>="+value2+"",null);
You can do something like this
DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
Date date1=df.parse("1990-01-01");
Date date2=df.parse("1995-01-01");
Date myDate=df.parse("1992-01-01"); // checking date
if((date1.getTime()<myDate.getTime())&&(myDate.getTime()<date2.getTime())){
System.out.println(df.format(myDate)+" is in this range");
}else{
System.out.println(df.format(myDate)+" is not in this range");
}
Since the format you want to use (yyyy-MM-dd) is ordered in the same way as a String (i.e. for any dates x and y you would choose, if x < y as a Date, then x < y as a String), you can simply store the dates as Strings (TEXT) in your database.
When selecting the values between them, you would just have to use a WHERE clause in your SELECT statement like this:
SELECT * FROM yourTable WHERE yourDateFieldName > ? and yourDateFieldName < ?
You can then use DateFormat.format to set the values for the ? parameters of your prepared statement. The first parameter would be the "start" date, and the second would be the "end" date. You can replace < with <= and > with >= if you want the items on start and end dates included.
This gives you a String representation of a Date. To convert from that to an actual Date object you can use date formatter's parse method (i.e. SimpleDateFormat.parse).
Another, "cleaner", approach would be to use the SQLite date and time functions (see here). While SQLite doesn't have a DATE type for storing date values, it has helper functions that you can use to interpret TEXT and NUMBER values as date in your statements.
If you don't need extra processing for your date values, I'd recommend going for the first solution as it should be faster because it merely compares TEXTs rather than parsing and extracting a date from them, then comparing the extracted date (I haven't compared the speed of the two approaches, so don't take my word for it on this one). This approach also has less code to write and maintain and the code is easier to read.
Sources:
SQLite data type - for the validity of comparing two TEXT values
SimpleDateFormat - Android documentation
You can use dates in yyyy-MM-dd format directly, JDBC will understand it. Assuming we a have a table t1 with c1 of DATE type
PreparedStatement ps = conn.prepareStatement("insert into t1 (c1) values (?)");
ps.setString(1, "2001-01-01");
ps.executeUpdate();
Reading dates is simple too
ResultSet rs = st.executeQuery("select c1 from t1");
rs.next();
Date date = rs.getDate(1);
ResultSet.getDate returns result as java.sql.Date whose toString method returns date in yyyy-MM-dd format

Date - Java to Sql table and sql table to Java through Joda Time

I am looking for a way to get today's date and pass to sql table and save there. Call the saved date and do some task with JODA TIME API. The changed Joda time Date to sql table and save there and process continues..
I tried this way,
//prints todays date
java.sql.Date sqlDate = new java.sql.Date(new Date().getTime());
//passes wrong date to the table like 1970-07-01 instead of 2013-03-01
String insert = "INSERT INTO TEST_TABLE VALUES(1,"+sqlDate+")";
pStmt = conn.prepareStatement(insert);
pStmt.executeUpdate();
//converting to joda time
LocalDate ld = new LocalDate(sqlDate);
//some calculations, and how to convert back to sql date?
What I am trying to do here is, A table with 3 columns (id, startdate, finishdate). id will be entered by user, start date should be automatically entered todays date. after some calculations with joda time and finish date will be set to date it is finished.
Code
String insert = "INSERT INTO TEST_TABLE VALUES(2,'"+timestamp+"')";
Error
Data type mismatch in criteria expression
//I have created table using MS access
//the format of the date column is Date/Time.
You Can use Timestamp here. java.sql.Timestamp extends java.util.Date, so anything you can do with a java.util.Date you can also do with a java.sql.Timestamp.
To convert LocalDateTime to Timestamp
Timestamp timestamp = new Timestamp(localDateTime.toDateTime().getMillis());
But if You still want to convert Timestamp into java.sql.Date then use this
java.sql.Date date = new java.sql.Date(timeStamp.getTime());

How to convert String to Time and insert it MySQL

I have a JSP page, so the user can insert the time when he/she arrives and goes from the place manually.
My question is: how can I convert that String, from the input box (JSP) to then insert it to query thus into my MySQL table.
I am using Java - servlet.
Thanks
You can use SimpleDateFormat to parse a String in the given pattern to a java.util.Date object.
Assuming that it's HH:mm, then you can do so:
String time = request.getParameter("time");
Date date = null;
try {
date = new SimpleDateFormat("HH:mm").parse(time);
}
catch (ParseException e) {
request.setAttribute("time_error", "Please enter time in format HH:mm");
}
Once having the java.util.Date object, you can store it in a TIME column by converting it to java.sql.Time and using PreparedStatement#setTime().
preparedStatement = connection.prepareStatement("INSERT INTO tablename (columname) VALUES (?)");
preparedStatement.setTime(1, new Time(date.getTime()));
preparedStatement.executeUpdate();

Categories