public void setEmployeeDetails(String month,String year,String day) throws
SQLException, ParseException
{
String sql="INSERT INTO EmployeeDetails (SiteName,EmployeeName,EmployeePhoneNumber,Date) VALUES(?,?,?,?)";
pStmt = conn.prepareStatement(sql) ;
String date=month+"/"+day+"/"+year;
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
java.util.Date parsed = format.parse(date);
java.sql.Date sql_date = new java.sql.Date(parsed.getTime());
System.out.println(sql_date);
}
public static void main(String args[]) throws SQLException, ClassNotFoundException, ParseException{
Employee_Details_DAO e=new Employee_Details_DAO();
e.setEmployeeDetails("12","2006","10");
}
I want to convert string date as format MM/ddd/yyy to sql ms access date format. But I got the output as 2006-12-10 but output should be as 12/10/2006
If System.out.println(sql_date); is displaying the date value as 2006-12-10 it is because it is using a default yyyy-mm-dd format, either from Java or from the operating system. It doesn't mean that the date is "wrong", it is just being displayed in a different way.
Always remember:
Date values do NOT have formats. They are just (numeric) values that correspond to a particular date.
[String] Representations of Dates do have a format. However, the format does not affect the value in any way. Whether it's 2006-12-25 or 12/25/2006 or December 25, 2006 or 2006 décembre 25 the Date value is still the same.
So, you don't need to worry about using any particular format for a Date parameter, just pass the value itself:
try (
Connection conn = DriverManager.getConnection(connStr);
PreparedStatement ps = conn.prepareStatement(
"INSERT INTO EmployeeDetails ([Date]) VALUES (?)")) {
String month = "12"; //
String year = "2006"; // sample data
String day = "10"; //
ps.setDate(1, java.sql.Date.valueOf(year + "-" + month + "-" + day));
ps.executeUpdate();
}
System.out.println(format.format(sql_date));//12/10/2006
java.sql.Date is a sub-class of java.util.Date. So we can format for java.sql.Date same as java.util.Date.
Related
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();
I am retrieving a date column from oracle DB and passing it as a string in a HTTP API call. Although the column value in DB is 26/08/2015 12:58:42, when I try :-
SimpleDateFormat sdfDate = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS'+03:00'");
this.requestDate = sdfDate.format(requestDate);
I get the String value as 2015-08-26T00:00:00.000+03:00 in API call URL.
Why is this happening and how to get the original hour, minutes and seconds?
EDIT: I was querying the date column by ResultSet.getDate("column_name"). Its resolved when I used ResultSet.getTimestamp("column_name")
public class TestTime {
public static void main(String[] args) throws SQLException, Exception {
Connection con = ConnectionDefinition.getOracleConnection();
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'+03:00'");
ResultSet rs = con.prepareCall("select sysdate from dual").executeQuery();
while(rs.next()){
System.err.println(sdfDate.format(rs.getTimestamp(1))); // try this
System.err.println(sdfDate.format(rs.getDate(1)));
}
}
}
getDate() method of ResultSet Interface Returns Date object which contains only date without time.
EX: 2015-08-26 (as per your input)
getTimestamp() method of ResultSet Interface returns Timestamp object which contains date as well as Time in 24 hours format.
Ex: 2015-08-26 12:58:42
after getting the respective objects you can apply format() method of SimpleDateFormat class to format the date.
I want to convert java.util.Date to java.sql.Date but I want hours, minutes, and seconds as well but java.sql.Date can be used only to store date(no time) . I tried the below code but it is giving only year, month, and day for the java.sql.Date object.
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
Date parsed = format.parse("20110210120534");
System.out.println(format.parse("20110210120534"));
java.sql.Date sql = new java.sql.Date(parsed.getTime());
System.out.println("SQL date is= "+sql);
Current output:
2011-02-10
Desired output:
2011-02-10 12:05:34
The java.sql.Date type is used to store only date (no time) information, as it maps to the SQL DATE type, which doesn't store time. What its toString() method does is:
Formats a date in the date escape format yyyy-mm-dd.
To achieve the desired output you can use java.sql.Timestamp, which stores date and time information, mapping to the SQL TIMESTAMP type. Its toString() method outputs what you need:
Formats a timestamp in JDBC timestamp escape format: yyyy-mm-dd hh:mm:ss.fffffffff, where ffffffffff indicates nanoseconds.
Example:
java.text.DateFormat format = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
java.util.Date date = format.parse("20110210120534");
java.sql.Timestamp timestamp = new java.sql.Timestamp(date.getTime());
System.out.println(timestamp); // prints "2011-02-10 12:05:34.0"
As other folks said, you need to use java.sql.TimeStamp.
public class Test {
public static void main(String[] args) {
java.util.Date date = new java.util.Date();
java.sql.Timestamp sqlTimeStamp = new java.sql.Timestamp(date.getTime());
System.out.println("util-date:" + date);
System.out.println("sql-timestamp:" + sqlTimeStamp );
}
}
http://tutorials.jenkov.com/java-date-time/java-sql-date.html
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));
When I convert String date like "18/09/13,02:01:51"
Using this method:
public static Date stringToDateFormat(String dateString) {
Date date = null;
try {
date = new SimpleDateFormat("dd/MM/yy,hh:mm:ss").parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
When I save this convert this date object to SQL Date and store it in PostgreSQL Database, I lose the time
2013-09-18 00:00:00
Here the DB insertion code"
String query = "INSERT INTO My_Table(my_date) VALUES (?)";
Date date = stringToDateFormat("18/09/13,02:01:51");
preparedStatement = connection.prepareStatement(query);
preparedStatement.setDate(1, new java.sql.Date(date.getTime()));
preparedStatement.executeUpdate();
Is it coding problem or DB configuration?
Thanks.
Your date string does not specify ms and is being rounded.
18/09/13,02:01:51 == 1379458917000
18/09/13,02:01:51.590 == 1379458917590
Update:
A format string which captures MS would be: dd/MM/yy,hh:mm:ss.SSS