Parsing a String into date with pattern:"dd/MM/yyyy" - java

I want to insert a date having this format MM/dd/YYYY for example:04/29/2010 to 29/04/2010 to be inserted into mysql database in a field typed Date.
So i have this code:
String dateimput=request.getParameter("datepicker");
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date dt = null;
try
{
dt = df.parse(dateimput);
System.out.println("date imput is:" +dt);
}
catch (ParseException e)
{
e.printStackTrace();
}
but it gives me those error:
1-date imput is:Fri May 04 00:00:00 CEST 2012 (it is not the correct value that have been entered).
2-dismatching with mysql date type.
I can not detect the error exactly.
Please help.

I do not really understand what you are trying to achieve. Parsing user input into a Date? Storing a Date into a MySQL DB field of type date (or datetiteme/timestamp) as an object or as a string?
1. Parsing user input
The code you propose parses user input into a java.util.Date correctly provided that the input is indeed in the expected format:
String dateimput="24/12/2009"; // Christmas Eve
java.text.DateFormat df = new java.text.SimpleDateFormat("dd/MM/yyyy");
java.util.Date dt = null;
try
{
dt = df.parse(dateimput);
System.out.println("date imput is:" +dt);
// = "date imput is:Thu Dec 24 00:00:00 CET 2009"
}
catch (java.text.ParseException e)
{
e.printStackTrace();
}
Notice that when a Date knows nothing about the format used for parsing it and outputting it as you do ('...+dt') calls its toString(), which by default uses the long date format. However there is no reason why that should be a problem for you. If you want to log it in a particular format, follow Daniel's suggestions.
2. Storing the date to the DB
If you store the date into a date /datetime/timestamp field via JDBC you have two options:
(A) Using string query and a Statement
Construct the insert query as a String and pass it to a Statement as in:
aConnection.createStatement().executeUpdate(
"insert into mytable(mydate) values(" + df.format(dt) + ")")
In this case you must make sure that the date string is in a format the DB can understand (such as yyyy-mm-dd for DB2).
(B) Using a PreparedStatement
Or, which is must safer because it prevents SQL injection, and also easier because it delegates the conversion of java types to the proper database form to the DB's JDBC driver, use a prepared statement:
PreparedStatement pstmt = con.prepareStatement(
"insert into mytable(mydate) values(?)");
pstmt.setDate(1, new java.sql.Date(dt.getTime()))

You just need to make sure the format you are using for parsing is the same as the one that is used by your datepicker.
UPDATE
On the database side, you just have to use PreparedStatement.setDate() and you don't need to worry about the format.

where you have:
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
try
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");

when trying DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); it gives me this: date imput is:Thu Apr 29 00:00:00 CEST 2010
I want to have 29/04/2010 00:00:00
When outputting the Date you also need to use DateFormat, otherwise it will just print what is returned by toString(). You could try System.out.println(df.format(dt));

Related

Insert date in oracle using prepared statemnt

My user interface returns a date as String (01/06/2016 2:30 am)to controller and I want to insert the into oracle 10 database by changing it from string to date and format to (dd-MMM-yy hh:mm:ss a) where the field is date type. Below is What I tried but getting Illegal Argument exception .
In controller I formatted to date and passed it to service layer through DTO
created : 01/06/2016 09:00 pm
SimpleDateFormat fromUser = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
SimpleDateFormat myFormat = new SimpleDateFormat("dd-MMM-yy hh:mm:ss a");
String reformattedStr = myFormat.format(fromUser.parse(created));
System.out.println("reformattedStr is : " + reformattedStr);
**reformattedStr 06-Jan-16 09:00:00 PM
Date formateDate=myFormat.parse(reformattedStr);
In service through prepared statement i am trying to insert , the date and other fields.
stmt.setTimestamp (8,new java.sql.Timestamp(news.getCreated().getTime()));
Can anyone please suggest?
Thanks for the help , I have updated the code, it might help some one.
If the column data type is timestamp, you don't need to do explicit conversion for the date. The statement.setTimestamp() method takes care of it.
There are two ways to create TimeStamp instance from a java.util.Date object.
new TimeStamp(date.getTime())
or
TimeStamp.value(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date))
The value returned by the news.getCreated().toString() method might not be returning the correctly formatted date - if it's returning formatted date.
Please refer to the javadoc for TimeStamp class for more information.
Thanks

String date to java date conversion

I have a string date something like below , I want to convert it in to java.util.Date.
String fromDate = "03/19/2009";
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
java.util.Date dtt = df.parse(fromDate);
System.out.println("the date is "+dtt);
But I am getting out put as Thu Mar 19 00:00:00 IST 2009, but I need it as 03/19/2009.
Please help me out.
You can use the same DateFormat and its SimpleDateFromat.format() to get the desired output.
String fromDate = "03/19/2009";
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
java.util.Date dtt = df.parse(fromDate);
System.out.println("the date is " + df.format(dtt));
You need to parse it again to the format you desire.
What you are currently printing is the value returned by the Data objects toString method.
You code works well. dtt actually holds the correct Date value.
When you print a Date, it uses toString().
If you want to print it in a specific format, you need to use another SimpleDateFormat and call format method.
Call method format on the SimpleDateFormat instance df.
try this
String DateStr="03/19/2009";
SimpleDateFormat sim=new SimpleDateFormat("MM/dd/yyyy");
Date d = new SimpleDateFormat("MM/dd/yyyy").parse(DateStr);
System.out.println(sim.format(d));
output 03/19/2009
You are printing a date not converted to string, so your result is correct, but if you want to print it as String, you shall reformat it as:
System.out.println("the date is " + df.format(dtt));

Java parsing String to a Date returns incorrect Date

I am storing my 2 Java date types as Date and Time for a MySQL database table. I am using the SimepleDateFormat("YYYY-MM-dd") to store the date in my database and it shows up as the correct date when i go to select it. However when i try to parse it back into a util.Date and create a new Event Object, it shows up as 30/12/2012 instead of 31/05/2013 as it is in the database. The time, when parsed into a util.Date and formatted prints out correctly. I am not sure why the Date is printing the wrong date, but the time is printing the correct time.
Database
+--------+--------------+-----------+
+ EVENT1 + 2013-05-31 + 02:30:00 +
+--------+--------------+-----------+
+ EVENT2 + 2013-05-31 + 01:00:00 +
+--------+--------------+-----------+
Prints:
Event1
30/12/2012
02:30
Event2
30/12/2012
01:00
It should be yyyy-MM-dd with lower case Ys. See here for what the capital Y means...
Y returns 2012 while y returns 2011 in SimpleDateFormat
Your pattern is wrong. (mm != MM, yyyy != YYYY ...)
Take a look at http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
try
String testDate = "2007-11-02T14:46:03";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date = formatter.parse(testDate);
But better way to store in database is to use timestamp instead of storing date and time separately
The proper method is rs.getDate(int). Take a look at
http://docs.oracle.com/javase/6/docs/api/java/sql/ResultSet.html#getDate(int)
With that method you get a java.sql.Date and if you want to transform it to a java.util.Date take a look at this Converting java.sql.Date to java.util.Date
You can even do this
Date date = rs.getTimestamp(2);
By the way, is better to have your date object independent on the format you want to use to show it.
try this...
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd");
Date date = dateFormat.parse(rs.getDate(2).toString());

Java Date Format

I have a table in MySQL server called Caller_List. In this table I have a single date column called call_date whose data type is Date. I have created a web page in which I have a SELECT Box for from_day (where all days 1 to 31 are stored), a SELECT box for month (where all month names from January to December are stored), a SELECT box for year (where all years from 2000 to 2012 are stored. Like I also have a SELECT box for to_day, to_month and to_year.
The problem is when I fetch these day,month and year from java servlet using request.getParameter() method, it is fetched as string data type and stored in variable called from_date and to_date. I concatenate from_day,from_month and from_year and store in the variable called from_date. Also I concatenate to_day,to_month and to_year and store in to_date. I concatenate them in the format year-month-day since MySQL understands this format.
I then pass the following query to retrieve data between these two from_date and two date:
select caller_name,call_date
from Caller_List
where call_date>='"+from_date+"' and call_date<='"+to_date+"'
I also tried the following query but in vain:
select caller_name,call_date
from Caller_List
where call_date between '"+from_date+"' and '"+to_date+"'
I also came to know that I need to convert from_date and to_date to date format before executing the query. But I am a novice in java, I do not know how to do it. Also I want the date in the format year-month-date. I do want to display time with date, please please help me!
If you only want to know how to parse a String to a Date in java, you could simplely use the SimpleDateFormat class.
final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
final Date fromDate = dateFormat.parse(from_date);
} catch (ParseException e) {
// ...
}
Assume that your from_date string is looks like 2012-09-16.
And if you want to display a date with time. You can also use the SimpleDateFormat.
final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
final String displayDate = dateFormat.format(new Date());
} catch (ParseException e) {
// ...
}
The displayDate should looks like 2012-09-16 20:13:25.
One more thing, you could compare a string type and a date type in MySQL. Just make sure your date string has the pattern "yyyy-mm-dd hh:mm:ss". Of course, you should use the preparedStatement.

different date format in java after fetching from oracle

In my db max date is as : 27-FEB-12
when i am fetching data by java from db that is:
select to_char(max(CREATE_DT),'dd-mm-yyyy') from PROFILE_DETAILS;
gives me 2012-02-27 00:00:00.0
How can i convert it to: 27-FEB-12( i am trying to use indian date format)
Any idea please
I don't know why you need to_char function in your query. If you are fetching data by jdbc, oracle could give you Date object. It is in your case much easier to convert into different format (String) in future.
anyway based on your current requirement, with to_char, you get a String 2012-02-27 00:00:00.0. now you want to get another string 27-FEB-12. you could do something like below(exception handling was omitted):
final String s = "2012-02-27 00:00:00.0";
String newDateString = new SimpleDateFormat("dd-MMM-yy").format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(s));
this will give you 27-Feb-12
String strDate = "2012-02-27 00:00:00.0";
String TimeZoneIds = TimeZone.getDefault().getID();
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S");
SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy");
sdf2.setTimeZone(TimeZone.getTimeZone(TimeZoneIds));
try {
Date date = sdf1.parse(strDate);
String strFinalDate = sdf2.format(date);
System.out.println(strFinalDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
In an Oracle DATE column there is no format; the string representation you see when you select max(create_dt)) from profile_details in SQL*Plus, say, is using an implicit format mask from your NLS settings, which appears to be DD-MON-RR in that client.
You JDBC call is applying an explicit format mask, which is the right thing to do if you want Java to treat it as a String, not least because it may have different NLS settings. But your mask doesn't match what you say you want; you're specifying DD-MM-YYYY when you want DD-MON-RR.
But it also looks like you're probably retrieving the value from the JDBC call with a getDate() call, and it's being implicitly cast back to a Java Date object type. If you want to treat it as a Date in Java, then you don't need the to_char in your select, and you need to use Java tools (e.g. SimpleDateFormat as #Andrew Logvinov suggests) to turn it into a String as needed. If you're only ever treating it as a String - for immediate display, say - then use getString() instead, and fix your date format mask in the query.
Edit
If you retrieve the value from JDBC with getDate() and want to see the value as a String in the format you specified, you need to do something like:
Date raw_date;
String string_date;
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy");
raw_date = <resultSet>.getDate(1);
string_date = sdf.format(raw_date);
select to_char(max(CREATE_DT),'dd-MON-yy') from PROFILE_DETAILS;

Categories