Date conversion jsp - java

I have jsp code that get date from the user (using html form) and I try to use the date in preparedStatament (sql).
the user enter date in format dd/mm/yyyy and i try to convert it into sql date yyyy-mm-dd...
this is the input type in the htl form:
<td><input type=date name="fdate"/></td>
<td><input type=date name="tdate"/></td>
this is the source code of dates.jsp (that run the sql):
SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd");
String fDateStr = request.getParameter("fdate");
String tDateStr = request.getParameter("tdate");
Date fdate = format.parse(fDateStr);
Date tdate = format.parse(tDateStr);
PreparedStatement prSelect = con.prepareStatement("select show_id,date,artist, name from shows where date between ? and ?");
prSelect.setDate(1, fdate);
prSelect.setDate(2, tdate);
This is the error that i get from setDate line:
"The method setDate(int, java.sql.Date) in the type PreparedStatement is not applicable for the arguments (int, java.util.Date)"
How can I solve it?

SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd"); should be like
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy",Locale.ENGLISH);
Try to use Locale for safety
Again Date fdate = format.parse(fDateStr); gives you java.util.Date you need to convert it o java.sql.Date to set it to PreparedStatement like this
public static Date convertUtilDateToSqlDate(java.util.Date date){
if(date != null) {
Date sqlDate = new Date(date.getTime());
return sqlDate;
}
return null;
}
Then
prSelect.setDate(1, convertUtilDateToSqlDate(fdte));
prSelect.setDate(2, convertUtilDateToSqlDate(tdate));

You must use java.sql.Date instead of java.util.Date
Try this
prSelect.setDate(1, java.sql.Date.valueOf(fDateStr));
prSelect.setDate(2, java.sql.Date.valueOf(tDateStr));

Related

Convertion to java.sql.Date for dd-MMM-yy format

I am doing jdbc and calling a procedure with date parameter but my db tables date format is in dd-MMM-yy format hence i converted my string date into dd-MMM-yy format but I am unable to setDate(1,sdt) cuz sdt must be in java.sql.Date type and java.sql.Date format is yyyy-MM-dd hence I need help
My procedure is defined thus:
PROCEDURE pStoreData(d_sumDttm IN DATE, i_Retval out number);
Short Code:
System.out.print("Enter report date:");
String sdate = scanner.nextLine();
final Date date = new Date();
final SimpleDateFormat format = new SimpleDateFormat();
format.applyPattern(dd-MMM-yy);
final String sysdt = format.format(date);
java.sql.Date sqldt = java.sql.Date.valueOf(sysdt);
callablestate = connection.prepareCall("{call Report.pStoreDate(?,?)}");
callablestate.setDate(1,sqldt);
callablestate.registerOutParameter(2,Types.REF_CURSOR);
callable.execute();
Update
Posting this update since OP seems to be struggling with how to use the original solution.
Dear OP,
Java instantiates date/time/date-time in just one way and then you can format it in your custom way. The database works the same way. So, it doesn't matter what format you display to the user or in what format the user enters the date; once you parse it into date/time/date-time object by applying the corresponding format, you just pass it to Java/DB and Java/DB will take care of the rest.
import java.time.LocalDate;
import java.util.Scanner;
import com.mysql.jdbc.CallableStatement;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter report date in MM-dd-yyyy format: ");
String strDate = scanner.nextLine();
LocalDate localDate = LocalDate.parse(strDate, DateTimeFormatter.ofPattern("MM-dd-yyyy"));
CallableStatement st = conn.prepareCall("{call Report.pStoreDate(?,?)}");
st.setObject(1, localDate);
st.registerOutParameter(2, Types.REF_CURSOR);
st.execute();
}
}
Original answer:
I suggest you do not use the outdated and error-prone java.util.Date. Use LocalDate instead as shown below:
LocalDate localDate = LocalDate.now();
PreparedStatement st = conn.prepareStatement("INSERT INTO mytable (columnfoo) VALUES (?)");
st.setObject(1, localDate);
st.executeUpdate();

inserting html5 datepicker into oracle getting exceptions

i am trying to insert html5 datepicker's date into Oracle table having datatype date,i've tried so many thing but i am still facing problem,plz help me to solve the issue.
static int addNotification(String date,String message)
{
int i=0;
try {
ps=con.prepareStatement("INSERT into ev values(?,to_date(?,'DD-MON-YYYY'))");
ps.setString(1, message);
DateFormat originalFormat = new SimpleDateFormat("yyyyMMdd");
DateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date dt = originalFormat.parse(date);
String formattedDate = targetFormat.format(dt);
System.out.println(formattedDate);
ps.setString(2, formattedDate);
// ps.setDate(2,formattedDate);
i=ps.executeUpdate();
}
everytime i am making changes , i am getting new exception for ex.
java.sql.SQLException: ORA-01861: literal does not match format string
java.text.ParseException: Unparseable date('YYYY-MM-DD')
plz help me to solve this problem.
You can use PreparedStatement.setDate(int parameterIndex,Date x) as follows.
try {
ps=con.prepareStatement("INSERT into ev values(?,?)");
ps.setString(1, message);
DateFormat originalFormat = new SimpleDateFormat("yyyyMMdd");
java.util.Date dt = originalFormat.parse(date);
ps.setDate(2,dt);
i=ps.executeUpdate();
}
if you want to convert the date then use,
DateFormat originalFormat = new SimpleDateFormat("yyyyMMdd");
if not would suggest you not capture html 5 datepickers data directly ,I would rather convert it using javascript and send it to response.
go through date class :-
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

converting string date into format yyyy-MM-dd to pass in hibernate criteria

I am getting the date in form of string to which i convert into below format
yyyy-MM-dd and finally the object should be of date type so that later I want
it to be added in hibernate criteria ..
public List<abc> eee(Long tradeId,
String sfsdf, boolean dfds,
String SettlementDate,
) {
query.add(Restrictions.eq("abcDate", <whatever date I am getting in yyyy-MM-dd>);
If it is a Date in the DB then you need to have the Object as a Date.
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY");
String myDate = "20-03-2014";
Date date = formatter.parse(myDate);
query.add(Restrictions.eq("abcDate", date));
String YourDate = "2014-03-20 03:30:12"
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date ConDate = dateFormat.parse(YourDate);

convert String to TIMESTAMP fo inserting time in table?

I created a table :
create table Appointment(
App_ID number primary key,
Doctor_ID number,
Patient_ID number,
App_Date Date,
App_Time TIMESTAMP,
App_Charges number);
i know how to convert String to java.sql.Date.
But for time i'm doing
String s1=time.getSelelctedItem().toString();//specifying time from a combo box
and then
st.setString(5,s1);
Please tell me the changes i need to make..
Thanks.
I'd use a java.util.Date in the middle:
// Specifying time from a combo box
String s1 = time.getSelelctedItem().toString();
// Convert String to Date according to the format
SimpleDateFormat df = new SimpleDateFormat("hh:mm");
Date date = df.parse(s1);
// Convert Date to Timestamp
Timestamp ts = new Timestamp(date.getTime());
// Set it:
st.setTimestamp(5, ts);
check the below code :
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateInString = "29/03/2014";
try {
Date date = formatter.parse(dateInString);
java.sql.Timestamp timest = new java.sql.Timestamp(date.getTime());
System.out.println(timest.getDate());
} catch (Exception e) {
e.printStackTrace();
}
so timest is the timestamp got from date which is parsed from datestring "29/03/2014" using SimpleDateFormat.

Cast String Date to new format Java

I am trying to cast a date format which is string resultset from database to a standard format, but using simpledateformat gives following error:
Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Date
at java.text.DateFormat.format(Unknown Source)
at java.text.Format.format(Unknown Source)
at CopyEJ.CopyEJ.main(CopyEJ.java:113)
RROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
JDWP exit error AGENT_ERROR_NO_JNI_ENV(183): [../../../src/share/back/util.c:838]
With De-bug I found out variable time_stmp has value "2013-04-19 17:29:06" I want to cast to this:
yyyyMMddhhmmss
Here's code:
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
ResultSet rs_dt = cmd1.executeQuery(dt);
String time_stmp = null;
while (rs_dt.next())
{
time_stmp = rs_dt.getString(1);
}
StringBuilder ts = new StringBuilder( df.format( time_stmp ) );
What is the best way to achieve this?
Your Simple DateFormat has the wrong datepattern. You have to parse it to date with the pattern of you DB, then parse it back to String.
Try it this way:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
ResultSet rs_dt = cmd1.executeQuery(dt);
String time_stmp = null;
while (rs_dt.next())
{
time_stmp = rs_dt.getString(1);
}
Date d = null;
try {
Date d = df.parse(time_stmp);
} catch (ParseException ex) {
Logger.getLogger(Prime.class.getName()).log(Level.SEVERE, null, ex);
}
SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddhhmmss");
StringBuilder ts = new StringBuilder( df2.format(d) );
By the way:
If you want your output to be in 24h-Format, then you have to use the pattern yyyyMMddHHmmss
The problem is, format of the date retrieved from DB is yyyy-dd-MM HH:mm:ss and you are trying to parse it with the format yyyyMMddhhmmss
You can do something like this
String date = "2013-04-19 17:29:06";
Date d = new SimpleDateFormat("yyyy-dd-MM HH:mm:ss").parse(date);
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyyMMddhhmmss");
System.out.println(outputFormat.format(d));
You need to use DateFormat.parse() here since the argument is of type String. DateFormat.format() on the other hand is used to format Date objects as String.
StringBuilder ts = new StringBuilder(df.format(df.parse(time_stmp)));
Also, it's recommended to save date/time data as a TimeStamp in database instead of a String.
Like it was mention you need to use
SimpleDateFormat.parse()
Also if your string is in the form
`2013-04-19 17:29:06`
You will want to construct your SimpleDateFormat for reading in like this
`yyyy-MM-dd HH:mm:ss` //make sure you use uppercase H for 24 hour times
Use SimpleDateFormat.parse() to convert a String to a Date.
Use SimpleDateFormat.format() to convert a Date to a String.
All together now:
SimpleDateFormat dbFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat stdFormat = new SimpleDateFormat("yyyyMMddhhmmss");
String s = stdFormat.format(dbFormat.parse(input));
You can modify the formats to suit your needs.
Hi you can use below code to format date as of your choice (Ex: yyyy-MM-dd HH:mm:ss)
Calendar calendar = Calendar.getInstance();
Date calDate = calendar.getInstance().getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("Calendar Date: " + calDate);
System.out.println("Your Choice Date format (yyyy-MM-dd HH:mm:ss): "+dateFormat.format(calDate));
This will work
SimpleDateFormat df = new SimpleDateFormat("YYYY-MM-dd hhhh:mm:ss");
String time_stmp ="2013-04-19 17:29:06";
Date date=df.parse(time_stmp);
StringBuilder ts = new StringBuilder( df.format( date ) );
System.out.println(ts);

Categories