java-How should one pass a date value to MySQL? - java

I have a column field called StartDate in MySQL of Date datatype. In my application, I defined a way to show the current date onn my page like this.
String today = CoreUtil.parseDate(new Date());
This basically returns the date in YYYY-MM-DD format and stored it in a string which is fine.
Now, I would like to pass this value into a function that inserts the value to the column StartDate.
The function I declared is as follow:
public void insert_update(String nodeid,String ts,Date startdt,Date enddt,int enable)
I am calling this function and passing the value today to it like below:
fileFacade.insert_update(...,....,today,....,...);
Now I am not an expert in this date thingy and seeing it wouldn't allow me to pass the value as I defined it as Date parameter, how should I handle this issue?
Should I convert it back to Date format and pass the value or does MySQL allow insertion of string value into a Date datatype column?
I just want to store the value in my table in YYYY-MM-DD format.
edit:
My function:
public void insert_update(String nodeid,String ts,Date startdt,Date enddt,int enable){
try {
// UrlLink attr = em.find(UrlLink.class,n);
String sql="UPDATE urllink SET STARTDT="+startdt+",ENDDT="+enddt+",ENABLE="+enable+"WHERE URL='f0="+nodeid+"&ts="+ts + "'";
em.createNativeQuery(sql).executeUpdate();
}catch (Exception e) {
e.printStackTrace();
}
}

You should not try to convert String into a Date in order to insert it into a table. You can use date type as is using preparedStatement, e.g.:
Date date = new Date();
PreparedStatement pStmt = connection.prepareStatement("<query>");
pStmt.setDate(1, date);
Here's the javadoc.
Update
If the purpose here is to display the date in specified format then I would strongly recommend storing the date as DATE in MySQL in format it while querying. The decision of how we store the date should not be driven by how it needs to be displayed on Front End as we might need different date formats to be displayed across multiple User Interfaces.

Pass String date in method parameter instead of Date type and then format that date type like this:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH);
formatter.parse(date)

Related

How to use Spring JPA for a custom query when trying to query by date?

I have a method where I'm trying to find all records based on a date. I'm using MySQL and the datatype is date. In the database the form is "2019-02-22".
How do I search for a date in this form using the Spring JPA repository?
I've tried to change the format using SimpleDateFormat format but then I get errors saying change the datatype to String. I do not want it to be string, I want the datatype to stay date. How is this done?
Here is the repository:
#Query(value="SELECT alttransport, customerfull, serviceadv, waitflag, apptdate FROM service WHERE apptdate=:currentDate", nativeQuery=true)
ArrayList<Serviceappt> getCurrentAppt(#Param("currentDate") Date currentDate);
Here is the method that gives me error:
#Override
public ArrayList<Serviceappt> getAppts(Date currentDate) {
final SimpleDateFormat dateFormat= new SimpleDateFormat("MM/dd/yyyy");
log.info("the date is: "+ dateFormat.format(currentDate));
ArrayList<Serviceappt> theList = apptRepository.getCurrentAppt(dateFormat.format(currentDate));
for(Serviceappt appt: theList){
log.info("the customer is: "+appt.getCustomerfull());
}
return theList;
}
The error is:
The method getCurrentAppt(Date) in the type ServiceapptRepository is
not applicable for the arguments (String).
How do I get this to work? Thanks!
Your getCurrentAppt method is waiting for a Date parameter, but you are passing dateFormat.format(currentDate) which returns a String.
SimpleDateFormat's format method is used to format a Date as String according to the specified format.
You don't need to format the date to match your database format, simply pass the date as argument :
ArrayList<Serviceappt> theList = apptRepository.getCurrentAppt(currentDate);
If you need to display it then you can format it, as you already did :
log.info("the date is: "+ dateFormat.format(currentDate));

How to insert the user entered value in jsp input type "time" to MYSQL database using JDBC

I have created a complaint registration form in JSP and in that there is an input field of type "time", also the time should not always be the current time hence I cannot use the CURRENTTIME() method of SQL.
Now while assigning it to the database I am getting HTTP Status 500 – Internal Server Error as "check the manual that corresponds to your MySQL server version for the right syntax to use near '.'20:20:00')' at line 1".
Here I have used the "setString()" method.
I have tried setTime() but that too is not working here, while setString() is working for the date value and date is properly being inserted in the DB.*/
Here is my jsp code for inserting the time in "test" table of "PCS" database .
<%# page import="java.sql.*" %>
String time=request.getParameter("time");
String url="jdbc:mysql://localhost:3306/pcs";
String uname="root";
String passw="publiccomplaint";
String query="insert into test values(?)";
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection(url,uname,passw);
PreparedStatement st=con.prepareStatement(query);
st.setString(1,time);
int count=st.executeUpdate();
st.close();
con.close();
What is the correct way in inserting the time into MYSQL DB from the input type="time" field of the form.?
You can try like this
String time = "15:30:18";
DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Date date = sdf.parse(time);
System.out.println("Time: " + sdf.format(date));
You should convert your date stored in string variable to java.util.date and then java.sql.date
String startDate="01-Feb-2013"; // Input String
SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy"); // New Pattern
java.util.Date date = sdf1.parse(startDate); // Returns a Date format object with the pattern
java.sql.Date sqlStartDate = new java.sql.Date(date.getTime());
System.out.println(sqlStartDate); // Outputs : 2013-02-01
Then
preparedStatement.setDate(1,sqlStartDate);
You should convert the time string to a java.time.LocalTime and use setObject to pass that as the parameter:
String time = "20:20:00"; // sample data
st.setObject(1, java.time.LocalTime.parse(time));

How to retrieve chosen date from JDatechooser?

I am using Eclipse to do a college project on Java. I realized that java does not have a built in date selector like C#, so I downloaded and added JDateChooser. I tried to retrieve the chosen date but it failed:
String Date = dateChooser.getDate(); //I want to the date to be retrieved as string
Any ideas? Is there some kind of initialization that I must do?
Retrieve the date that the user selected by calling getDate(), which returns a Date object. Then convert that object into a String by calling SimpleDateFormat.format():
Date d;
SimpleDateFormat sdf;
String s;
d = dateChooser.getDate(); // Date selected by user
sdf = SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); // Or whatever format you need
s = sdf.format(d); // Viola
See also: Question 5683728
If I have the right component, the Java Docs show that the getDate method returns Date
getDate
public java.util.Date getDate() Returns the date. If the
JDateChooser is started with a null date and no date was set by the
user, null is returned. Returns: the current date
String dob =new SimpleDateFormat("dd-MMM-yyyy").format(jDateChooser1.getDate());

How to display date in Jtable with the date value only?

I insert date into database by the following code
String sql = "Insert Into Purchase (Purchase_ID, Purchase_Date) values (?,Date())";
and yes, my database store the value with the current date only
But when I retrieve the Purchase Date from my database into JTable, the result display the date when I insert and with the time 00:00:00:00.
How can I want to display the result with the date only?
Use a SimpleDateFormat. For instance:
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
String s = format.format(yourDate);

How to get date like this Sept 15th 2011 in oracle query result instead of 15sep2011_00:00:00?

I am executing a query
select level as VERSION,
name as DESCRIPTION,code as CODE,created as RELEASEDATE
,SUBSTR(name, INSTR(name, '.',-1)+1) as TYPE
from mytable
where code = 'HX56UO'
which gives result like
Type Version Description Release Date
.exe 3.0.2 MPC560xB MCAL Autosar 3.x 15sep2011_00:00:00
I need release date like this Sept 15th 2011 and i need to set this result value in a bean set method.
public void setLastDate(java.util.Calendar newLastPubDate) {
lastDate = newLastDate;
}
what type casting i need to do in setting the above value from result set
since the set method is of calender.
i tried like setting the value like this
if (rs.getDate("RELEASEDATE") != null ) {
Bean.setLastPubDate(rs.getdate"RELEASEDATE"));
}
But it is not date format,its of calender how to set the value.
Please help me solving this.
Thanks.
if (rs.getDate("RELEASEDATE") != null ) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(rs.getDate("RELEASEDATE"));
Bean.setLastPubDate(calendar);
}
EDIT:
When you later want to convert the calendar to a string (to display it), you can use a SimpleDateFormat.
String formatted = new SimpleDateFormat("dd MMMM yyyy").format(bean.getLastPubDate().getTime());
As your created column is a VARCHAR2 - very bad practice to not store a date as a DATE but we'll skip that for now - you need to convert it to a date type somewhere, and in the query is possibly simplest:
select level as VERSION,
name as DESCRIPTION,
code as CODE,
TO_DATE(created,'DDMONYYYY_HH24:MI:SS') as RELEASEDATE,
SUBSTR(name, INSTR(name, '.',-1)+1) as TYPE
from mytable
where code = 'HX56UO'
You can still use getDate() from the resultset, and need to convert that Date to a Calendar object as you call your bean method:
Bean.setLastPubDate(Calendar.getInstance().setTime(rs.getDate("RELEASEDATE"));

Categories

Resources