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')
Related
I'm trying to parser String to Timestamp because I need to save this data on bbdd mysql.
String dateString: "2018-10-17T22:37:10.000+0000";
java.sql.Timestamp timeStampDate = null;
try {
DateFormat formatter;
formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
Date date = (Date) formatter.parse(dateString);
timeStampDate = new Timestamp(date.getTime());
} catch (ParseException e) {
log.debug("ERROR parser String to Timestamp to save bbdd. ", e.getMessage());
}
When I run my app I get this catch message:
ERROR parser String to Timestamp to save bbdd. Unparseable date: "2018-10-17T22:37:10.000+0000"
Can anybody help me?
change your mask to
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS");
so you have
java.sql.Timestamp timeStampDate = null;
String dateString = "2018-10-17T22:37:10.000+0000";
try {
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date date = formatter.parse(dateString);
timeStampDate = new Timestamp(date.getTime());
} catch (ParseException e) {
e.printStackTrace();
}
By the way you should not need to cast the Date
Apologies for my slackness, in my haste I did not test the output and as per #andreas comment, the correct mask is actually yyyy-MM-dd'T'HH:mm:ss.SSSZ
java.time
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSXX");
String dateString = "2018-10-17T22:37:10.000+0000";
OffsetDateTime odt = OffsetDateTime.parse(dateString, formatter);
System.out.println("Parsed datetime: " + odt);
Output from this code is:
Parsed datetime: 2018-10-17T22:37:10Z
For saving into MySQL it’s good to use a datetime object, but the Timestamp class has design problems and is now long outdated. I am sorry that I don’t have the experience with MySQL, but I think the following should work:
PreparedStatement ps = myDatabaseConnection.prepareStatement(
"insert into my_table (my_timestamp) values (?)");
ps.setObject(1, odt);
Link: Oracle tutorial: Date Time explaining how to use java.time.
What is the correct format for date filtering - JDBC to SQL
I have been trying to use the following with an MS-Access DB
SELECT doctorbusiness.dateofreport,
doctorbusiness.patientname,
doctorbusiness.labcomm,
doctorbusiness.xcomm,
doctorbusiness.spccomm,
doctorbusiness.ecgcomm
FROM doctorbusiness
WHERE doctorbusiness.doctorname = '"+selectedDoc+"'
AND (( doctorbusiness.dateofreport >= # "+sd+" # )
AND ( doctorbusiness.dateofreport <= # "+ed+" # ))
selectedDoc is in String and sD and eD in date format.
The query runs fine in MS-Access but gives the following exception :
net.ucanaccess.jdbc.UcanaccessSQLException: unknown token:
UPDATE
public void printDoctorIncome() {
Date startDate = easypath.docB_startDate_jxdp.getDate();
Calendar calSD = Calendar.getInstance();
calSD.setTime(startDate); // convert your date to Calendar object
int daysToDecrement = -1;
calSD.add(Calendar.DATE, daysToDecrement);
Date real_StartDate = calSD.getTime();
SimpleDateFormat sdF1 = new SimpleDateFormat("dd-MM-yyyy");
String sD = sdF1.format(real_StartDate);
JOptionPane.showMessageDialog(null, sD);
Date endDate = easypath.docB_endDate_jxdp.getDate();
Calendar calED = Calendar.getInstance();
calED.setTime(endDate); // convert your date to Calendar object
int daysToIncrement = +1;
calED.add(Calendar.DATE, daysToIncrement);
Date real_endDate = calED.getTime();
SimpleDateFormat sdF2 = new SimpleDateFormat("dd-MM-yyyy");
String eD = sdF2.format(real_endDate);
JOptionPane.showMessageDialog(null, eD);
String selectedDoc = easypath.drname_jlist.getSelectedValue().toString();
String sql = "SELECT doctorBusiness.dateofreport, doctorBusiness.patientName, doctorBusiness.labComm, doctorBusiness.xComm, doctorBusiness.spcComm, doctorBusiness.ecgComm FROM doctorBusiness WHERE doctorBusiness.doctorname ='"+selectedDoc+"' AND (doctorBusiness.dateofreport >= ?"+sD+"? AND doctorBusiness.dateofreport <= ?"+eD+"?)";
try {
conn = connectDB.getConnection();
psmt = conn.prepareStatement(sql);
rs = psmt.executeQuery();
doctorIncome.docIncomePrint_table.setModel(DbUtils.resultSetToTableModel(rs));
doctorIncome dI = new doctorIncome();
dI.setVisible(true);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error");
e.printStackTrace();
}
}
This is the code I am using
With JDBC better way to do it is use setDate/Time/Timestamp methods of PreparedStatement. And you shouldn't care about concrete DB's date format.
Date dateFrom = ...
Date dateTo = ...
String sql = "... where myDate >= ? and myDate <= ? "
preparedStatement.setDate(1, dateFrom);
preparedStatement.setDate(2, dateTo);
Using a PreparedStatement is a good idea. But you can also use either #MM/dd/yyyy# or #yyyy-MM-dd# (with or without hours:minutes:seconds).
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.
hi i have to convert timestamp to date after check the query and return the count value.
my database have date(1344399208,1344399269),status(Q,Q).
This is my code:
public class GetCurrentDateTime {
public int data(){
int count=0;
java.sql.Timestamp timeStamp =new Timestamp(System.currentTimeMillis());
java.sql.Date date = new java.sql.Date(timeStamp.getTime());
System.out.println(date);
//count++;
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/xcart-432pro","root","");
PreparedStatement statement = con.prepareStatement("select * from xcart_orders where status='Q' AND date=CURDATE()");
ResultSet result = statement.executeQuery();
while(result.next()) {
// Do something with the row returned.
count++; //if the first col is a count.
}
}
catch(Exception exc){
System.out.println(exc.getMessage());
}
return count;
}
}
Here the date is saved in timestamp format.but i like to convert date(yyyy-mm-dd) format.its done successfully.ya i got the output is 2012-08-08.but i have to check the query today date+status=Q .so how is that date is save in variable and call that variable in query.so how is wrote query for above condition.after check the condition and display the returns count value on my tomcat console.How is to do.please help me
Partial Answer to your Question
Date Examples
Examples borrowed from Code Ranch and SO posts
// Get system time
Timestamp SysTime = new Timestamp(System.currentTimeMillis());
java.util.Date UtilDate = new java.util.Date(Systime.getTime());
java.sql.Date SQLDate = new java.sql.Date(Systime.getTime());
// Date + Time + Nano Sec
System.out.println(SysTime);
// Date + Time
System.out.println(UtilDate);
// Date
System.out.println(SQLDate);
Formatting Dates
// Apply Format
Date InDate = SQLDate; // or UtilDate
DateFormat DateFormat = new SimpleDateFormat("yyyy MM dd");
String DisplayDate = DateFormat.format(InDate);
System.out.println(DisplayDate);
Please note that I am new to java, hence verify if it works.
Comparing dates
See this SO post:
How to compare dates using Java
To convert date to the date format specified:
int timestamp = 1231342342342; // replace with timestamp fetched from DB
Date date = new Date(timestamp);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
String dateString = sdf.format(date); //convert to yyyy-mm-dd format
From what I understand from the edit, you want the query to be something like this:
PreparedStatement statement = con.prepareStatement("select * from xcart_orders where status='Q' AND date='"+dateString+"'");
I'm assuming that the date is stored in string format in the DB since you asked it to be converted into a particular format.
From comments:
To get midnight date:
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
To get all entries within a 24 period:
"select * from xcart_orders where status='Q' AND date between " + cal.getTimeInMillis() + " and " + (cal.getTimeInMillis() + 86400000l);
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());
}