Convert Date into MYSQL Date Format - java

I have this MySQL Date data for 6 months in this format:
2010-01-01 to 2010-07-01
But from the UI the ToDate and FromDate are passed in this format:
Jan 1, 2010 and July 1, 2010
Please tell me how can I convert this data into MySQL equivalent format?

First create a SimpleDateFormat for parsing your input from the UI:
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy");
Next parse an input into a java.sql.Date (which is unfortunately named and different from java.util.Date). So for example:
java.sql.Date date = new java.sql.Date(sdf.parse(fromDate).getTime());
Finally use the date to pass to JDBC when making your database queries. Such as:
Connection con; // assuming you have a database connection
PreparedStatement ps = con.prepareStatement("SELECT * FROM table WHERE x = ?");
ps.setDate(1, date);
ResultSet resultSet = ps.executeQuery();

Related

JDBC date to SQL date

I have been using Java to store some records from a csv file.
One of these records is a date. The problem here is I am using JDBC to store these records in a database. Now, the Date object of Java is showing an error while putting it into the database. I have been stuck on this for a while. Please let me know how to solve this. I have used type Date in mysql for storing it into the database. Here is the part creating the problem.
DateFormat d1 = new SimpleDateFormat("yyyy-MM-dd");
Date d = new Date();
System.out.println(d1.format(d));
String sql = "INSERT INTO TESTING"+
"VALUES("+"DATE_FORMAT("+d+","+"'%Y-%m-%d'"+"))";
stmt.executeUpdate(sql);
If I execute this directly in MySqlWorkBench, it is storing the date properly. But through JDBC it is a problem.
The error is as shown below :
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Jun 30 14:04:03 IST 2016,'%Y-%m-%d'))' at line 1
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3277)
at com.mysql.jdbc.Statement.executeUpdate(Statement.java:1402)
at com.mysql.jdbc.Statement.executeUpdate(Statement.java:1317)
at payex.writeDB(payex.java:221)
at payextestdrive.main(payextestdrive.java:11)
You add d.toString() to the SQL command when you want to add the formatted date string. Also a space is missing between the table name and VALUES:
String sql = "INSERT INTO TESTING VALUES(DATE_FORMAT(" + d1.format(d) +",'%Y-%m-%d'))";
The error message is pretty clear
right syntax to use near 'Jun 30 14:04:03 IST 2016,'%Y-%m-%d'))'
The format you provided is MMM DD HH:mm:ss Z YYYY, but the system expects %Y-%m-%d
Try
DateFormat d1 = new SimpleDateFormat("yyyy-MM-dd");
Date d = new Date();
System.out.println(d1.format(d));
String sql = "INSERT INTO TESTING"+
" VALUES("+"DATE_FORMAT('"+d1.format(d)+"',"+"'%Y-%m-%d'"+"))";
stmt.executeUpdate(sql);
or simply
DateFormat d1 = new SimpleDateFormat("yyyy-MM-dd");
Date d = new Date();
System.out.println(d1.format(d));
String sql = "INSERT INTO TESTING"+
" VALUES('"+d1.format(d)+"')";
stmt.executeUpdate(sql);

How to change the sysdate format in eclipse for queries?

Date today = new Date();
SimpleDateFormat df = new SimpleDateFormat ("dd/MM/yy");
String date = df.format(today);
System.out.println(date);
PreparedStatement sql = con.prepareStatement("select count(*), name, status from tablename where file_date = date group by name, status");
ResultSet rs = sql.executeQuery();
However, the sysdate format in SQL is dd/MM/yy
But the date format in Eclipse is yyyy-MM-dd HH:mm:ss.fff
How do I convert it in query so that I can get dd/MM/yy format?
What about passing a true SQL Date, don't bother about internal string representation for dates.
PreparedStatement sql = con.prepareStatement("select count(*), name, status from tablename where file_date = ? group by file_name, status");
sql.setDate(1, new java.sql.Date(new java.util.Date().getTime());

Mapping Date and Time to MySQL

I have created a table in MySQL as :
CREATE TABLE scheduled(sid INT,id INT,tweet VARCHAR(255),sdate DATE,
stime TIME,PRIMARY KEY(sid),FOREIGN KEY(id) REFERENCES usercred(id));
I receive both Date and Time from the HTML input field. Date received from the HTML field looks like :
4/30/2014
How can I map this in Java ? After receiving both Date and Time and after mapping them correctly , I will commit the transaction or will update the table/entry.
could use the parse() method in the SimpleDateFormat object:
SimpleDateFormat sdf = new SimpleDateFormat("M-dd-yyyy");
String dateInString = "4-30-1982"";
Date date = sdf.parse(dateInString);
System.out.println(date);
In JDBC-layer inside PreparedStatement or ResultSet you work with the mapping java.sql.Date (for SQL-DATE) and java.sql.Time (for SQL-TIME). Then you can wrap both types like:
java.sql.Date sqlDate = ...; // from ResultSet
DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); // or M/d/yyyy
String htmlFormat = df.format(sqlDate);
And in reverse:
String htmlFormat = ...;
DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); // or M/d/yyyy
java.util.Date d = df.parse(htmlFormat);
java.sql.Date sqlDate = new java.sql.Date(d.getTime());
// use result in PreparedStatement for INSERT or UPDATE
Attention: Both approaches use the standard timezone of the server where this code is running. In case of doubt you should probably set the timezone UTC. Similar code for the TIME-part.

SimpleDateFormat value insert to ms db

I formatted my jspinner as:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
JSpinner.DateEditor de = new JSpinner.DateEditor(jSpinner1, "MM/dd/yyyy");
jSpinner1.setEditor(de);
and try to insert the value of jSpinner to ms db:
String SQLString = "INSERT INTO Table1(DateToday)VALUES(?)";
stmt = con.prepareStatement(SQLString);
stmt.setDate(1, new java.sql.Date(sdf.format(jSpinner1.getValue())));
but I still get an error.
Please do me some favor if you could give any sample code to get it right.
Many many thanks...
For SQL Server, you could use a string value
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
....
stmt.setString(1, sdf.format(jSpinner1.getValue()));
but the date should have worked so the error is likely that you have some constraint on the table that is not satisfied.

How do I set a full date & time sql using java, and not just the date?

I am trying to set a timestamp in my database using java, however in my table all I get is the date, and no time (i.e., looks like "2010-09-09 00:00:00").
I am using a datetime field on my mysql database (because it appears that datetime is more common than timestamp). My code to set the date looks like this:
PreparedStatement ps = conn.prepareStatement("INSERT INTO mytable (datetime_field) VALUES (?)")
java.util.Date today = new java.util.Date();
java.sql.Date timestamp = new java.sql.Date(today.getTime());
ps.setDate(1, timestamp);
ps.executeUpdate();
How do I set the date to include the time?
Edit: I changed the code as per below, and it sets both the date and the time.
PreparedStatement ps = conn.prepareStatement("INSERT INTO mytable (datetime_field) VALUES (?)")
java.util.Date today = new java.util.Date();
java.sql.Timestamp timestamp = new java.sql.Timestamp(today.getTime());
ps.setTimestamp(1, timestamp);
ps.executeUpdate();
Use java.sql.Timestamp and setTimestamp(int, Timestamp). java.sql.Date is date-only, regardless of the type of the column it's being stored in.
Not exactly sure what you need to use, but
ps.setDate();
expects a column type of Date. So it's normalizing it, removing the time.
Try
ps.setTimetamp();
You could use :
private static String getTimeStamp() {
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return f.format(new Date());
}

Categories

Resources