My java code generates two Strings:
String myDate = "10/10/2013";
String myTimestamp = "2013-10-09 14:30:20";
I need to feed these values to a prepared statement, so that I could upload them using jdbc to Teradata
Here is what I tried :
String in = " INSERT INTO " + myTab + " VALUES (?,?) ";
PreparedStatement prst = null;
prst = connection.prepareStatement(in);
// add date
prst.setDate(1, (Date) new SimpleDateFormat("MM/dd/yyyy").parse(myDate));
//add timestamp
prst.setDate(2, (Date) new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(myTimestamp));
The above code compiles but does not work. I get an empty string error . How can I convert a String into Teradata types DATE, TIMESTAMP in order to add them to the prepared statement ?
You could use the java.sql.Date constructor that takes a long, by using Date#getTime() and changing from
prst.setDate(1, (Date) new SimpleDateFormat("MM/dd/yyyy").parse(myDate));
to something like
prst.setDate(1, new java.sql.Date(new SimpleDateFormat("MM/dd/yyyy")
.parse(myDate)).getTime());
and the other one
prst.setDate(2, new java.sql.Date(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.parse(myTimestamp)).getTime());
Try this:
prst.setDate(1, new java.sql.Date(new SimpleDateFormat("MM/dd/yyyy").parse(myDate).getTime()));
This will convert your date then create a new sqlDate.
prst.setTimestamp(2, new java.sql.Timestamp(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(myTimeStamp).getTime());)
for the timestamp use setTimeStamp not setDate.
Related
There is a lot of discussion here, but what I have tried isn't working. Till now in my tables I store the dates as a string, but I assume this isn't the right way... So I created a table:
CREATE TABLE "TRANSACTIONS" (
"date" DATETIME,
...
}
I want to store the date like 2016-11-04 10:50, so I use:
String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(Calendar.getInstance().getTime());
I use prepared Statements to insert records in DB and when I try to do this:
stm.setDate(1, timeStamp);
I get that String cannot be converted to Date. So I convert it to DATE
String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(Calendar.getInstance().getTime());
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date datee = formatter.parse(timeStamp);
and then I get java.util.Date cannot be converted to java.sql.Date so I tried this:
String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(Calendar.getInstance().getTime());
java.sql.Date sqlDate = java.sql.Date.valueOf(timeStamp);
which when I run it, I get java.lang.IllegalArgumentException
java.sql.Date represents a date, not a date and time.
You are getting this error because you are passing "yyyy-MM-dd HH:mm" and throws java.lang.IllegalArgumentException
String d1 = "2016-10-11";
java.sql.Date d = null ;
d.valueOf(date1);
System.out.println(d.valueOf(date1));
`
This will run without any exception.
For your required format you should use java.sql.Timestamp
String date1 = "2016-10-11 10:45";
SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd HH:mm");
java.util.Date d2 = sm.parse(date1);
Timestamp time = new Timestamp(d2.getTime());
System.out.println(time);
Output - 2016-10-11 10:45:00.0
I wish to produce a current timestamp in the format of yyyy-MM-dd HH:mm:ss. I have written up the following code, but it always gives me this format yyyy-MM-dd HH:mm:ss.x
How do you get rid of the .x part ?
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = df.format(new Date());
Timestamp timestamp = Timestamp.valueOf(currentTime);
I need to have a timestamp type for writing into mysql.
Probably you're looking at the String representation the Timestamp object gives in your database engine or its Java representation by printing it in the console using System.out.println or by another method. Note that which is really stored (in both Java side or in your database engine) is a number that represents the time since epoch (usually January 1st 1970) and the date you want/need to store.
You should not pay attention to the String format it is represented when you consume your Timestamp. This can be easily demostrated if you apply the same SimpleDateFormat to get a String representation of your timestamp object:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = df.format(new Date());
Timestamp timestamp = Timestamp.valueOf(currentTime)
//will print without showing the .x part
String currentTimeFromTimestamp = df.format(currentTime);
Anyway, if you want the current time, just create the Timestamp directly from the result of new Date:
Timestamp timestamp = new Timestamp(new Date().getTime());
You can insert the timestamp as a String to the MySQL table. Your String representation in currentTime is sufficient.
The best way to write Timestamp or any data type in Java is to use PreparedStatement and an appropriate method
PreparedStatement ps = conn.prepareStatement("update t1 set c1=?");
ps.setTimestamp(1, new java.sql.Timestamp(new Date().getTime()));
ps.executeUpdate();
I have created a table in MySQL as :
CREATE TABLE scheduled(sid INT,id INT,tweet VARCHAR(255),sdate DATE,
stime TIME,PRIMARY KEY(sid),FOREIGN KEY(id) REFERENCES usercred(id));
I receive both Date and Time from the HTML input field. Date received from the HTML field looks like :
4/30/2014
How can I map this in Java ? After receiving both Date and Time and after mapping them correctly , I will commit the transaction or will update the table/entry.
could use the parse() method in the SimpleDateFormat object:
SimpleDateFormat sdf = new SimpleDateFormat("M-dd-yyyy");
String dateInString = "4-30-1982"";
Date date = sdf.parse(dateInString);
System.out.println(date);
In JDBC-layer inside PreparedStatement or ResultSet you work with the mapping java.sql.Date (for SQL-DATE) and java.sql.Time (for SQL-TIME). Then you can wrap both types like:
java.sql.Date sqlDate = ...; // from ResultSet
DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); // or M/d/yyyy
String htmlFormat = df.format(sqlDate);
And in reverse:
String htmlFormat = ...;
DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); // or M/d/yyyy
java.util.Date d = df.parse(htmlFormat);
java.sql.Date sqlDate = new java.sql.Date(d.getTime());
// use result in PreparedStatement for INSERT or UPDATE
Attention: Both approaches use the standard timezone of the server where this code is running. In case of doubt you should probably set the timezone UTC. Similar code for the TIME-part.
My database column datatype is timestamp. How do I insert the current date and time using a PreparedStatement or Statement?
I have tried this:
java.util.Date date = new java.util.Date();
System.out.println("Current Date : " + dateFormat.format(date));
pstmt.setDate(9, new java.sql.Timestamp(date.getTime()));
But the value inserted in the table is 1328847536746. This not right, i am using sqlite
There is a separate Timestamp value class in java.sql.
pstmt.setTimeStamp(9, new java.sql.Timestamp(date.getTime()));
The javadoc explains:
public class Timestamp
extends Date
A thin wrapper around java.util.Date that allows the JDBC API to identify this as an SQL TIMESTAMP value.
Use setTimestamp().
pstmt.setTimestamp(9, Timestamp.valueOf("2002-03-13 11:10:15.01"));
This is the code I've used so far to get it done
Timestamp nextRunTimestamp = null;
if(endDate != null || !endDate.equalsIgnoreCase(""))
{
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
dateFormat.parse(endDate);
Calendar tempDate = dateFormat.getCalendar();
tempDate.set(Calendar.HOUR, nextRunTime.get(Calendar.HOUR));
tempDate.set(Calendar.MINUTE, nextRunTime.get(Calendar.MINUTE));
tempDate.set(Calendar.SECOND, nextRunTime.get(Calendar.SECOND));
tempDate.set(Calendar.MILLISECOND, nextRunTime.get(Calendar.MILLISECOND));
if(nextRunTime.before(tempDate) || nextRunTime.equals(tempDate))
{
nextRunTimestamp = new Timestamp(nextRunTime.getTimeInMillis());
}
}
else
{
nextRunTimestamp = new Timestamp(nextRunTime.getTimeInMillis());
}
statement.setTimestamp(2, nextRunTimestamp);
statement.setInt(3, result.getInt("id"));
statement.executeUpdate();
DateFormat df = new SimpleDateFormat(yyyy/MM/dd HH:mm:ss); // any Date format
System.out.println("Current Date : " + df.format(new Date()));
pstmt.setDate(9, to_timestamp(df.format(new Date()),'YYYY/MM/DD HH24:MI:SS'));
Here you can use TO_DATE('todayDate', 'YYYY/MM/DD HH24:MI:SS') or
TO_TIMESTAMP('todayDate', 'YYYY/MM/DD HH24:MI:SS')
I am trying to set a timestamp in my database using java, however in my table all I get is the date, and no time (i.e., looks like "2010-09-09 00:00:00").
I am using a datetime field on my mysql database (because it appears that datetime is more common than timestamp). My code to set the date looks like this:
PreparedStatement ps = conn.prepareStatement("INSERT INTO mytable (datetime_field) VALUES (?)")
java.util.Date today = new java.util.Date();
java.sql.Date timestamp = new java.sql.Date(today.getTime());
ps.setDate(1, timestamp);
ps.executeUpdate();
How do I set the date to include the time?
Edit: I changed the code as per below, and it sets both the date and the time.
PreparedStatement ps = conn.prepareStatement("INSERT INTO mytable (datetime_field) VALUES (?)")
java.util.Date today = new java.util.Date();
java.sql.Timestamp timestamp = new java.sql.Timestamp(today.getTime());
ps.setTimestamp(1, timestamp);
ps.executeUpdate();
Use java.sql.Timestamp and setTimestamp(int, Timestamp). java.sql.Date is date-only, regardless of the type of the column it's being stored in.
Not exactly sure what you need to use, but
ps.setDate();
expects a column type of Date. So it's normalizing it, removing the time.
Try
ps.setTimetamp();
You could use :
private static String getTimeStamp() {
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return f.format(new Date());
}