Update/ Retrieve /Inserting date field - java

I am having difficulties while updating a date field into the Database. The field type in the DB is Date/Time.
Now, I am trying to update the field name "R_Date".
Currently, I am using the SQL Expression in my jsp"
UPDATE request SET request_date ='"+Request_Date+"'"; , But it is not accepting.
In the select statement I am using a normal select, I tried to use to_char or to_date, but it is not accepting the format of "DD-MMM-YYYY"
So, can you please help me to retrive/Update/Insert date field in the format of "DD-MMM-YYYY" the date field?

The normal practice to store a timestamp in the DB (thus, java.util.Date in Java side and java.sql.Timestamp in JDBC side) is to use PreparedStatement#setTimestamp().
Date requestDate = getItSomehow();
Timestamp timestamp = new Timestamp(requestDate.getTime());
preparedStatement = connection.prepareStatement("UPDATE request SET request_date = ?");
preparedStatement.setTimestamp(1, timestamp);
The normal practice to obtain a timestamp from the DB is to use ResultSet#getTimestamp().
Timestamp timestamp = resultSet.getTimestamp("request_date");
Date requestDate = timestamp; // You can just upcast.
To convert between java.util.Date and java.lang.String you normally use SimpleDateFormat:
// Convert from String to Date.
String requestDateAsString = "09-Aug-2010";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);
Date requestDate = sdf.parse(requestDateAsString);
// Convert from Date to String.
String anotherDateAsString = sdf.format(someDate);
See also:
PreparedStatement tutorial
How to avoid Java code in JSP file (!!!)

I think you should use MON instead of MMM.
Have you tried something like:
UPDATE request
SET request_date = to_date('" + Request_Date + "', 'DD-MON-YYYY')
Hope you realize that as your statement stands (if it worked), it would update every row in the request table (not sure if that's your intention or not but I thought I'd point it out).

You need to check what date format you are trying to insert, and try using to_date method with appropriate format.
Following is referenced from : http://infolab.stanford.edu/~ullman/fcdb/oracle/or-time.html
Oracle's default format for DATE is "DD-MON-YY".
If you want to retrieve date in particular format you need to use :
TO_CHAR(<date>, '<format>')
Similarly if you need to insert/update date with input of date other than in standard format, you need to use :
TO_DATE(<string>, '<format>')
where the <format> string can be formed from over 40 options. Some of the more popular ones include:
MM Numeric month (e.g., 07)
MON Abbreviated month name (e.g., JUL)
MONTH Full month name (e.g., JULY)
DD Day of month (e.g., 24)
DY Abbreviated name of day (e.g., FRI)
YYYY 4-digit year (e.g., 1998)
YY Last 2 digits of the year (e.g., 98)
RR Like YY, but the two digits are ``rounded'' to a year in the range 1950 to 2049. Thus, 06 is considered 2006 instead of 1906
AM (or PM) Meridian indicator
HH Hour of day (1-12)
HH24 Hour of day (0-23)
MI Minute (0-59)
SS Second (0-59)

Related

Timezone conversion in Grails leads to wrong dates

I'm about to deal with time zones in Grails (Java). Here Java 7 is used and Grails 2.3.7.
I have a WebApp where each user is assigned a timeZoneID. If a user enters a date, it only consists of day, month and year. I want to set the time automatically.
The date entered by the user (e.g. 01.10.2018, german format) should be saved in the DB (MySQL) in UTC format.
When the date is displayed to the user, it is formatted according to the user's time zone.
Many timeZoneIDs work fine with my code (Europe/Berlin, Hont_Kong, ....), but America/New_York for example doesn't and I don't understand why.
The code to parse and save a date is as follows:
//endDate is 31.10.2018
def format = messageService.getMessage(code: 'default.date.short.format')
//--> dd.MM.yyyy for DE and MM/dd/yy for EN
println("Use format: " + format)
SimpleDateFormat sdf = new SimpleDateFormat(format);
//set timezone (America/New_York)
sdf.setTimeZone(TimeZone.getTimeZone(user.timeZoneID))
//parse endDate
Date parsedEndDate = sdf.parse(endDate)
//create a calendar instance (e.g. America/New_York)
Calendar calendarEnd = Calendar.getInstance(TimeZone.getTimeZone(user.timeZoneID));
//set time
calendarEnd.setTime(parsedEndDate);
//set hour/minute automatically
calendarEnd.set(Calendar.HOUR_OF_DAY, 23)
calendarEnd.set(Calendar.MINUTE, 59)
//at this point it should be 31.10.2018, 23:59 (german format, timezone America/New_York)
//Convert to UTC before saving date in DB (MySQL)
calendarEnd.setTimeZone(TimeZone.getTimeZone('UTC'))
//save the date
def obj = new Foo(date:calendarEnd).save(flush:true)
The code inside my view (gsp) to display a date is as follows:
<g:formatDate
timeZone="${user.timeZoneID}"
date="${fooInstance?.calendarEnd}"
format="${message(code: 'default.date.format', default: 'MM/dd/yyyy, hh:mm a')}"/>
Inside the DB I get 2018-11-01 00:59:00
Inside my view (GSP) it results in 31.10.2018, 19:59, instead of 31.10.2018, 23:59
Thank you very much for your help.
The problem is in convert step:
//Convert to UTC before saving date in DB (MySQL)
calendarEnd.setTimeZone(TimeZone.getTimeZone('UTC'))
Because you are just changing the time zone so it is using the given time and date as if it is the UTC time zone.
Java 1.7 and before are somewhat unwieldy in regards to the Time API so a lot of people use Joda Time.
Otherwise you can use the advice from this question resulting in something like:
calendarEnd.add(Calendar.MILLISECOND, TimeZone.getTimeZone('UTC').getOffset(parsedEndDate.getTime())
This is not tested and could be wrong as the offset calculation might be diffrent

insert java date time into Oracle

Oracle date format on server is MM/DD/YYYY HH24:Mi:SS
I would like to insert a variable which contains a date with timestamp into Oracle date column.
I am getting error while inserting date into Oracle "date column ends before format picture ends".
All I want is append specific timestamp to java string date and insert that string/date format into Oracle database
example:
String incoming_date = request.getParameter("insert_date"); //this comes as a string in dd-mon-yyyy format
formatted_incoming_date = incoming_date + " 00:00:01"; //I want to append time factor to above variable with 00:00:01
insert into testtable values(formatted_incoming_date);
Try this
insert into testtable values(TO_DATE (formatted_incoming_date, 'dd-mon-yyyy hh24:mi:ss);
Why you try to insert date as a string? It seems like there is an implicit conversion from string to date in Oracle. Can java.sql.Date be used instead?
Anyway, as long as date comes in format dd-mon-yyyy you have to convert it either into java.sql.Date object or in proper for Oracle string representation as MM/DD/YYYY HH24:Mi:SS i.e.
incoming date "05-12-2016" string for Oracle "12/05/2016 00:00:00"

Comparing to get seconds difference between java and mysql datetime

I read a mysql date time field into one string e.g.
String arriveTime = rs1.getString("arriveTime");
Next step I try to get the current date and time using java to be similar format like the one I got from mysql.
DateFormat outDf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateTimer=null;
Date date = Calendar.getInstance().getTime();
currentDateTimer=outDf.format(date);
How can I minus the currentDateTime and arriveTime to get the net results in seconds. I would prefer to do it purely via java
First, I would not read a MySQL date-time into a String. I would change this,
String arriveTime = rs1.getString("arriveTime");
to
java.sql.Date arriveTime = rs1.getDate("arriveTime");
Then you can use basic subtraction to get the result in milliseconds, then divide by a thousand to get that in seconds - so
long diff = new java.util.Date().getTime() - arriveTime.getTime();
System.out.println(diff / 1000);
I read a mysql date time field into one string
If the column is varchar type it is ok you can read it using resultsetObject.getString()
But if your column type is Date then is it always recommended to get the value using resultset.getDate()
Mysql stores date in the format yyyy-MM-dd
I try to get the current date and time using java to be similar format
like the one I got from mysql.
When you do resultset.getDate() it will give you the java.sql.Date in format yyyy-MM-dd

Java: Insert into a table datetime data

I am trying to insert into a variable in MS- SQL database the current date and the time.
I use this format:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
and I get this as a result 2013-01-28 09:29:37.941
My field in the database is defined datetime and as I have seen in other tables which have the same field, the date and the time is written exactly like this 2011-07-05 14:18:33.000.
I try to insert into the database with a query that I do inside a java program, but I get this error
SQL Exception: State : S0003 Message: The conversion of a varchar
data type to a datetime data type of the value is out of range. Error
: 242
My query is like that:
query = "INSERT INTO Companies CreatedOn"+
"VALUES ('" + dateFormat.format(cal.getTime()) + "')"
but I don't understand what I am doing wrong.
According to the error description, you are inserting an incorrect type into the database. See JDBC to MSSQL. You should convert Calendar to Timestamp.
Try using:
PrepareStatement statement
= connection.prepareStatement("INSERT INTO Companies CreatedOn VALUES(?)");
java.sql.Timestamp timestamp = new java.sql.Timestamp(cal.getTimeInMillis());
statement.setTimestamp(1, timstamp);
int insertedRecordsCount = statement.executeUpdate();
First of all, do NOT use string concatenation. Have you ever heart about SQL injection?
Correct way how to do that is to use prepared statement:
Idea is you define statement with placeholders and than you define value for those placeholders.
See #Taky's answer for more details.
dateFormat#format this method returns formatted string not Date object. Database field is DateTime and it is expecting java.sql.Timestamp to be inserted there not String according to docs.
To conform with the definition of SQL DATE, the millisecond values
wrapped by a java.sql.Date instance must be 'normalized' by setting
the hours, minutes, seconds, and milliseconds to zero in the
particular time zone with which the instance is associated.
Try java.sql.Timestamp object instead of String in query and I'd recommend you to use PreparedStatement.
This is because you are trying to save String date value to Date type DB field.
convert it to Data dataType
You can also use the datetime "unseparated" format yyyymmdd hh:mm:ss
You could use Joda framework to work with date/time.
It maps own date/time types to Hibernate/SQL types without problem.
When you set parameters in HQL query joda carries about right type mapping.
If you want to store current date and time then you should use MYSQL inbuilt method NOW().
for brief documentation refer http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html . so your code will be like.
INSERT INTO Companies CreatedOn VALUES(NOW())"
However If you want to do it using java Date-util then it should be
Calendar cal = Calendar.getInstance();
java.sql.Timestamp timestamp = new Timestamp(cal.getTimeInMillis());

Date Format Confusion

in my App User Selects Date like 2013-01-02
but in MySql DB the column format is like 02-Jan-2013 so want change the Date Format
my code is:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");
SimpleDateFormat formatter1 = new SimpleDateFormat("dd-mmm-yyyy");
Date start_date = (Date)formatter.parse(GBRF.getStart_date());//GBRF.getStart_date() returns Form Data as 2013-01-02
String dt=formatter1.format(start_date);
Date sd=(Date)formatter1.parse(dt);
at the End sd print Date like this Wed Jan 02 00:01:00 IST 2013
i dont want that format..
just i want like 02-Jan-2013
give me an idea..
Thanks in Advance
You can format Date into String with SimpleDateFormat, after that if you try to print date instance it will invoke toString() method of Date class which has no change in output and you can't alter that output because it is coming from toString() implmentation
Note: in your format you need to use M for month (note capital M)
A Date object does not have a format in itself. It holds just a point in time. The format comes into play when you convert it to or from a String.
Also note that m in the format is used for minutes not months. So you probably want a format like dd-MMM-yyyy.
Try
System.out.println(formatter1.format(sd));
to get the date printed as you like it.
You need to change your date format first :
`SimpleDateFormat formatter1 = new SimpleDateFormat("dd-MMM-yyyy");`
In your case, if you just print dt, it should print date in the required format instead of converting it into Date object again i.e. sd
When you are printing sd, without any formatting it will print the default String implementation of Date object which is exactly what you are seeing as an output

Categories