wrong value when converting String date to date Object - java

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

Related

How can I read an Excel Date and store it into my database?

I am trying to read an Excel Date value and store it into my database.
The following code is what I've got:
Date birthdate = null;
case 8:
birthdate = cell.getDateCellValue();
break;
The switch case is to store the Date in a variable and to put it into an array afterwards.
Identity id = new Identity(BSN, sort, birthdate, place);
I store multiple of those values into an arraylist.
for(Identity id : Identities) {
System.out.println(id.toString());
idmc.insertID(""+id.getBSN(), id.getSort(), id.getBirthdate(), id.getPlace());
}
The getter and setter for date is obvious, but I'll post it just in case.
public void Birthdate (Date birthdate) {
this.birthdate = birthdate;
}
public Date getBirthdate() {
return birthdate;
}
Then to insert the values I get from the Array, I use this method:
public String insertID(String BSN, String SoortID, Date UitgiftedatumID, String UitgifteplaatsID) {
String returning = null;
try {
query = "insert into Identiteit values(?,?,?,?);";
pst = connection.prepareStatement(query);
pst.setInt(1, Integer.parseInt(BSN));
pst.setString(2, Sort);
pst.setDate(3, birthdate);
pst.setString(4, place);
int response = pst.executeUpdate();
returning = response +" Records has/have been edited";
} catch (SQLException e) {
returning = " ";
}
return returning;
}
However, the line: pst.setDate(3, UitgiftedatumID); says: Incomatible types: java.util.Date cannot be converted to java.sql.Date.
I've tried casting like: pst.setDate(3, (java.sql.Date) UitgiftedatumID);
But unfortunately that didn't work out for me.
There are two Date classes in Java: java.util.Date (a general-purpose date-time class) and java.sql.Date (JDBC-related class that represents date (with no time component)). PreparedStatement#setDate() method accepts the latter as its second parameter.
To convert an instance of java.util.Date to an instance of java.sql.Date, you could do the following:
java.util.Date UitgiftedatumID = ... // some value
java.sql.Date sqlDate = UitgiftedatumID == null ? null : new java.sql.Date(UitgiftedatumID.getTime());

sql delete based on date

I am a total noob to java and sqlite. This should be simple, but I have tried and searched and can't get it to work. I have a date field in SQL that I am formatting as a sql date (MM/dd/yy). I want to delete based on a date passed. For the moment, I am only trying to display rows based on a passed date.
My code to run the query is:
String query = "select * from Peter1Score where DateSort='"+convertSQLDate("09/20/15")+"'";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
My converSQLDate() is:
public static java.sql.Date convertSQLDate (String sqlDateIn)
{
java.sql.Date returnDate = null;
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
Date parsed;
try
{
parsed = formatter.parse(sqlDateIn);
java.sql.Date sqlDate = new java.sql.Date(parsed.getTime());
returnDate = sqlDate;
}
catch (ParseException e)
{
e.printStackTrace();
}
return returnDate;
}
I am passing 09/20/15 just for test. I have a record with that date, but it doesn't get selected.
You're not binding any variables into the statement (using the setXY() methods of PreparedStatement). Instead, you're concatenating a string value (result of Date.toString()) into the query literal.
Try this instead:
String query = "select * from Peter1Score where DateSort=?";
PreparedStatement pst = connection.prepareStatement(query);
pst.setDate(1, convertSQLDate("09/20/15"));

String Date conversion into sql date format MM/dd/yyyy?

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.

How to insert string type timestampto in to sql server 2008 r2 table

I am trying to insert records from excel file into database table. The excel file contains time stamp as "05/10/13 03:47 PM IST". I want to save the time stamp in db as datetime, so that later i may able to fire query on datetime constraint. In java i am using prepared statement. I am using datetime2(7) data type in table.
value of timeStampt = 05/10/13 03:47 PM IST
private void insertToDb(String vh, String timeStamp, String location, double tempReal, double tempFixed) throws ParseException{
conn = DbHandler.getConnection();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy hh:mm a");
java.util.Date utilDate = sdf.parse(timeStamp);
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
String query = "INSERT INTO [DATALOGGER_TEMP_REPORT](vehicle_no,time_stamp,location,temp_real,temp_fixed)values(?,?,?,?,?)";
try {
pstmt= conn.prepareStatement(query);
pstmt.setString(1,vh);
pstmt.setDate(2, sqlDate);//(2, date);
pstmt.setString(3, location );
pstmt.setDouble(4, tempReal);
pstmt.setDouble(5, tempFixed);
pstmt.executeUpdate(); // execute insert statement
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Currently, In database table timestamp value is stored as = 2013-10-05 00:00:00.0000000
Rather, i want my table to store timestamp as 05/10/13 03:47 PM IST
The problem here depends on what type of column you are trying to store into in the sql server db.
see http://msdn.microsoft.com/en-us/library/ms186724.aspx
If you are simply using a SQL Date type, then this only has the accuracy of one day.
I am assuming that the java.util.Date utilDate is correctly holding the datetime.
Try it with the java.sql.Timestamp type instead of java.sql.Date. This should be appropriate. It works the same way as with java.sql.Date.
Your code would then contain:
....
java.sql.Timestamp sqlTS = new.java.sql.Timestamp(utilDate.getTime());
...
pstmt.setTimestamp(2, sqlTS);
...

How to Convert String To DateTime in java

I am trying to store date in sql server 2005
i am used "datetime" data type in sql server
and in java program i am passing string as date
ex.
String DateStr = "12/12/2013";
Date d = new Date();
java.sql.Date d1 = new java.sql.Date(d.getTime());
String sql = "INSERT INTO info (date) VALUES ( ? )";
try {
pstmt = con.prepareStatement(sql);
pstmt.setDate(1, d1);
pstmt.executeUpdate();
} catch (SQLException e) {
System.out.println("Error:" + e);
}
the above code is working...but i want to use String DateStr = "12/12/2013";
insted of d.getTime() bcoz i passed date as string to java function by using jquery datepicker
You need to use a SimpleDateFormat to parse your String to a date and then use that date.
Date d = new SimpleDateFormat("dd/MM/yyyy").parse(DateStr); // This throws a ParseException
// Rest everything stays pretty much the same
java.sql.Date d1 = new java.sql.Date(d.getTime());
...
public long convertLong(String value) {
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date getDate = null;
long returnDate = 0l;
try {
getDate = (Date) formatter.parse(value);
returnDate = getDate.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return returnDate;
}
Input: 12/12/2013
Output: 1386786600000
First convert string in datetime object than you can directly pass d1 to your code
String DateStr = "12/12/2013";
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy ");
DateTime dt = formatter.parseDateTime(DateStr);
String sql = "INSERT INTO info (date) VALUES ( dt )";
try {
pstmt = con.prepareStatement(sql);
pstmt.setDate(1, d1);
pstmt.executeUpdate();
}
catch (SQLException e) {
System.out.println("Error:" + e);
}

Categories