Parsing Date in Java - java

Good day everyone! I have a problem regarding my "date". It needs to be parsed but I don't know how to do it. Can someone help me by suggesting fixes on my code?
<%
String format = "yyyy-MM-dd";
DateFormat df = new SimpleDateFormat(format);
String faculty = request.getParameter("faculty");
String absent_date = request.getParameter("absent_date");
int intFaculty = Integer.parseInt(faculty);
System.out.println(faculty);
System.out.println(df.parse(absent_date));
java.sql.Date absentdate = new java.sql.Date(df.parse(absent_date).getDate());
Absences abs = new Absences();
abs.setFaculty_id(intFaculty);
abs.setAbsent_date(absentdate);
int result = AbsencesImpl.AddAbsences(abs);
if (result == 0)
{
%>
<jsp:forward page="ListAbsences.jsp">
<jsp:param name="msg" value="Record Successfully Added"/>
<jsp:param name="ret" value="meron"/>
</jsp:forward>
<%
}
%>
For the result and error in Console:
5
Tue May 01 00:00:00 CST 2012
java.sql.SQLException: 3 values for 2 columns
I found this but I dont know how to implement this on my codes.
SimpleDateFormat parserSDF=new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
Im using Eclipse Indigo, Sqlite, and Apache Tomcat
Insert Statement (Im using MVC)
public int AddAbsences(Absences abs)
{
Connection con = null;
PreparedStatement pstmt;
ConnDB conn = new ConnDB();
String sql = "INSERT INTO absences( faculty_id, absent_date) VALUES(?, ?)";
try{
con = conn.connect();
try{
pstmt = con.prepareStatement(sql);
pstmt.setInt(1, abs.getFaculty_id());
pstmt.setDate(2, abs.getAbsent_date());
pstmt.executeUpdate();
}catch(Exception e){
System.out.println(e);
}
con.close();
}catch(Exception e){
System.out.println(e);
}
return 0;
}

I will recommend to use
df.parse(absent_date).getTime()
instead of
df.parse(absent_date).getDate()
And also, I suspect that you have table absences with 3 columns, but you try to insert only 2 values. If one of values from table is id, then I suspect this value is not autogenerated.
Hope it will help you.

Try to formulate a insert statement which will work from the database management console (which ever is your database), then try to substitute the same in the code with arguments. There by you will get the date format also. There are some sql date functions which you can use in the query itself which will convert the date from your code readable format.
eg: in MsSQL - cast ('20120312' as datetime) will convert the string date 12-03-2012 into date time.
try to search for sql date functions for your type of database.

Related

how can i improve the search using date in sql database in java

I made a software using the java language and MS SQL Server as the database. The problem am facing is that when I search for a date range using two dates, it's giving items which I have not requested.
For example, if I need items from 1st to 7th October, it includes items on the 11th, 12th, 13th, 14th, 15th, 16th, etc.
the date format am using MMM d,yyyy
I have used the following code
String val1 = ((JTextField)jdate1.getDateEditor().getUiComponent()).getText();
String val2 = ((JTextField)jdate2.getDateEditor().getUiComponent()).getText();
String sql = " select * from Report_details where Date between '"+val1+"' and '"+val2+"' ";
// conn is some Connection
PreparedStatement myStmt = conn.prepareStatement(sql);
ResultSet rs = myStmt.executeQuery();
if(rs.next()){
// do stuff
}
Do not trust user input.
String sql = "select * from Report_details where Date between ? and ?";
....
Date dt1 = new SimpleDateFormat("MMM d,yyyy").parse(val1);
// better yet, have your date picker return a Date object
....
myStmt.setDate(1, dt1);
....
should be the way to go (or setTime or setTimestamp, depending on your table definition)
NB: do not copy paste this, just a hint to get you off in the right direction.

"incompatible datatypes in combination" error with query on date value

The intent of my overall program is to fetch values from Access database and display in jtable for a particular date.
I have a table in access database where for_date field is stored as a Date/Time field and format is Short date(dd-MM-yyyy). Now my program requires me to retrieve the rows from the database for a particular date.I used SimpleDateFormat to convert it in the format as access database but it gives error. The error I get is:- net.ucanaccess.jdbc.UcanaccessSQLException:UCAExc:::3.0.4 incompatible datatypes in combination.This exception may happen if you add integers representing units of time directly to datetime values using the arithmetic plus operator but without specifying the unit of date.In this specific case you have to use,for example, +1 DAY
My code is as follows:-
String table_sel = "ISGS_table";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date1 = sdf.format(report_date.getDate());
try{
String sql = "Select reporting_date as REPORTING_DATE,for_date as FOR_DATE,outage_date as OUTAGE_DATE,outage_time as OUTAGE_TIME,stat_detail as STATION_DETAILS,res_date as RESTORATION_DATE,rest_time as RESTORATION_TIME,rest_reason as RESTORATION_REASON from " + table_sel+" where for_date='" + date1 + "'";
Connection con = null;
Statement st = null;
ResultSet rs = null;
PreparedStatement pst = null;
String dbURL = "jdbc:ucanaccess://C:\\Users\\Dell_PC\\Documents\\SYSTEM_OUTAGE_REPORT.accdb";
con = DriverManager.getConnection(dbURL);
st = con.createStatement();
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
con.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
You are receiving that error message because you are passing the value for for_date as a string literal. UCanAccess follows the Access SQL convention of using hash marks (#) as the delimiter for date/time literals.
So, this will fail with the error you cited
... WHERE for_date = '2017-02-03'
whereas this will work
... WHERE for_date = #2017-02-03#
Note that it would be considered better form if you were to use a PreparedStatement with
... WHERE for_date = ?
and pass the date value using PreparedStatement#setDate.

Saving a Date to MySQL database [duplicate]

Can anyone help me with a sample JSP code to store date in a MySql database through JDBC?
When I try to execute the code given below, I get the following exception:
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: '' for column 'date' at row 1
How to overcome this problem? Following is my code:
Connection con = null;
String StaffName = request.getParameter("StaffName");
// String subcode = request.getParameter("subcode");
String hourId = request.getParameter("hourId");
if (hourId == null)
hourId = "";
String day = request.getParameter("day");
if (day == null)
day = "";
String date = request.getParameter("date");
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/StaffAllocation", "root", "success");
// PreparedStatement stat = con.PrepareStatement();
String updateString = "INSERT INTO tblstaffallocation (StaffName,hourId,daysId,date) VALUES (?,?,?,?)";
PreparedStatement preparedStatement = con.prepareStatement(updateString);
preparedStatement.setString(1, StaffName);
preparedStatement.setInt(2, 0);
preparedStatement.setInt(3, 0);
preparedStatement.setString(4, date);
} catch (Exception e) {
out.print(e);
}
To set date to prepared statement you need change type of value:
String date = request.getParameter("date");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); // your template here
java.util.Date dateStr = formatter.parse(date);
java.sql.Date dateDB = new java.sql.Date(dateStr.getTime());
now convert String date to java.sql.Date and use another method:
preparedStatement.setDate(4,dateDB);
I had a similar error. It turns out I just needed to update the jar version for mysql-connector-java (using maven)
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>...</version>
</dependency>
Try reformating the date
String date = new SimpleDateFormat("yyyy-MM-dd")
.format(new Date(request.getParameter("date")));
and then insert into the database.
Note that request.getParameter("date") should be in format 11/20/2013 for this to work or you can use a similar way to achieve.
Make sure that the Date value that you are trying to insert into the table is exactly in the format defined in the date column of your table.
I know this is an old thread, but none of these solutions solved the problem for me. What worked for me was to upgrade hibernate to version 5.2.10.Final (see this SO post).
Running Spring Boot and Spring Data JPA 1.5.4.RELEASE and hibernate 5.2.10.Final.
If someone will have similar error for entity field with Data type annotated as #Temporal, the solution for me was to replace annotation value TemporalType.TIMESTAMP by TemporalType.TIME:
#Temporal(TemporalType.TIMESTAMP)
private Date dateField;
should be like this:
#Temporal(TemporalType.TIME)
private Date dateField;
Another way to resolve this problem without any changes in code (at least for me) was to run application on higher Tomcat version, hope it will help.
Accepted answer only handles date, not datetime. Anyways...
My problem was it didn't accept really old datetime's. I generated date in .net environment, where default date was "1900-01-01 01:01:01". I had to change date to somthing later in time... Ooops.
My error message:
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: '1900-01-01 01:01:01' for column 'added' at row 1

Inserting custom date and current time into Oracle database using string variables

So what I want to do is set a custom date along with the current time into the DATE type in the Oracle database.
I get the string from textField in the form of mm/dd/yyyy
String tdate = textDate.getText().trim();
To simplify the details lets just insert the DATE into a small table.
Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
String current_time = hour+":"+minute+":"+second;
now we have tdate as the string of date and current_time as the current time.
to put into a database with table defined as :
create table transaction(
tranaction_num integer,
time_of_transaction DATE);
now in jdbc
PreparedStatement pStmt = Conn.prepareStatement("insert into transaction values(?,?));
pStmt.setString(1, "1");
pStmt.setString(2, "to_date( '"+tdate+" "+current_time+"','mm/dd/yyyy hh24:mi:ss')");
pStmt.executeUpdate();
This gives me an error as below
ORA-01858: a non-numeric character was found where a numeric was expected
I know I am doing something wrong but I have tried so many things to get this working. I don't mind getting the current time some other way as long as it is working
Any help would be appreciated
You should parse the date string before handing it over to the database and you should use setInt() for the first parameter instead of setString()
SimpleDateFormat parser = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date date = parser.parse(tdate+" "+current_time);
String sqlStmt = "INSERT INTO transaction(tranaction_num, time_of_transaction) VALUES(?,?)";
PreparedStatement pStmt = Conn.prepareStatement(sqlStmt);
pStmt.setInt(1, 1);
pStmt.setDate(2, new java.sql.Date(date.getTime()));
pStmt.executeUpdate();
If you want to pass a string, you probably want something like
String sqlStmt = "insert into transaction values(?,to_date(?,'mm/dd/yyyy hh24:mi:ss'))"
PreparedStatement pStmt = Conn.prepareStatement(sqlStmt);
pStmt.setString(1, "1");
pStmt.setString(2, tdate+" "+current_time);
pStmt.executeUpdate();
From a good coding standpoint, however, you would be much better served doing a setInt for the first parameter and a setDate on the second parameter rather than passing everything as strings.
Instead of
pStmt.setString(1, "1");
Use:
pStmt.setInt(1, 1);

Insert Date field into DB

I am having a textbox field in my jsp called "req_date". The user is selecting a date from a javascript calendar in the format of "DD-MON-YY" ex. "29-aug-2010".So, now I am stuck while trying to insert it in the DB.
I tried " String queryString = "INSERT INTO Charity (req_date) VALUES (?)", but it is not inserting. How do I solve tis out.
The req_date is type of date in the DB.
Can you please help
Date format depends upon Database you use.
For reference Date formats with Oracle.
so your query should look like :
String queryString = "INSERT INTO Charity (req_date) VALUES (to_date('29-aug-2010', 'dd-mon-yyyy'))"
This is just to answer your question. But I will prefer usage of PreparedStatement as also suggested in other answers.
Your code using PreparedStatement should look something like following: (NOTE: I have not tested this code )
String formatIn = "dd-MMM-yyyy";
SimpleDateFormat sdfi = new SimpleDateFormat(formatIn);
java.util.Date inDate = sdfi.parse("29-Aug-2010");
java.sql.Date sqlDate = new java.sql.Date(inDate.getTime());
PreparedStatement prest = con
.prepareStatement("INSERT INTO Charity (req_date) VALUES (?)");
prest.setDate(1, sqlDate);
int row = prest.executeUpdate();
Use a PreparedStatement and its setDate(..). Or use a timestamp (long).
It depends on your database, PostgreSQL does recognize this format:
SELECT CAST('29-aug-2010' AS date);
Result:
'2010-08-29'
In most cases, you'd better use the ISO-format yyyy-mm-dd.

Categories

Resources