I am trying to use setDate() in a PreparedStatement, however the date that I have is in the format of 2008-07-31. The code is:
pstmt.setDate(f++, (Date) DateFormat.getDateInstance(DateFormat.DEFAULT).parse(value.substring(0, 10)));
However, it gives me the error:
Exception in thread "main" java.text.ParseException: Unparseable date: "2008-07-31"
Why is this?
If you have a very specific date, don't ask Java to use a default date format - set it yourself.
For example:
DateFormat parser = new SimpleDateFormat("yyyy-MM-dd");
Date date = parser.parse(value.substring(0, 10));
You should also potentially set the time zone of the parser... my guess is that UTC is the most appropriate time zone here.
Note that this has nothing to do with prepared statements as such - it's just date parsing.
(As an alternative to using DateFormat and SimpleDateFormat, you could use Joda Time which has a nicer API and thread-safe formatters/parsers. You can ask Joda Time to convert from its own types to Date values. Possibly overkill if you only need it for parsing here, but if you're doing anything else with dates, it's well worth looking into.)
You need make sure the default DateFormat is in yyyy-MM-dd format (usually it's a config in OS), or you can use SimpleDateFormat or java.sql.Date to parse date string.
java.util.Date d;
SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd");
d = sdf.parse ("2008-07-31");
// or
d = java.sql.Date.valueOf ("2008-07-31");
or, you could just set parameter as String, if the underlying database driver support the VARCHAR/CHAR to DATE conversion.
DateFormat.DEFAULT points to MEDIUM format and MEDIUM format looks like Jan 12, 1952. So, you may have create a SimpleDateFormat object with the format you are using.
I think there is mismatch in the format of the date that you are providing as input and the format in which you have specified while formatting which is default in your case.
SimpleDateFormat parser = new SimpleDateFormay("yyyy-MM-dd");
Try using the same format for both the dates.
First convert String to Date and then set that to PreparedStatement. Check with below code.
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd");
Date convertedDate = dateFormat.parse(dateString);
I'd use
pstmt.setDate(f++,
new java.sql.Date(
new SimpleDateFormat("yyyy-MM-dd")
.parse(value.substring(0, 10))
.getTime()
)
);
Related
I want to convert from string to date using Java 8.
I can easily convert using SimpleDateFormat and yyyy-MM-dd format
String startDate2="2017-03-24";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(new java.sql.Date(sdf1.parse(startDate2).getTime()));
output:
2017-03-24
String startDate2="2017-03-24";
SimpleDateFormat sdf1 = new SimpleDateFormat("uuuu-MM-dd");
System.out.println(new java.sql.Date(sdf1.parse(startDate2).getTime()));
But when I use 'uuuu-MM-dd' instead of 'yyyy-MM-dd'
output :
1970-03-24(wrong)
now in Java 8:
String startDate1="2017-03-23";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd");
But I don't know how I can get the date which would be sql date type same as above correct output.
java.sql.Date has a static valueOf method that takes a Java 8 LocalDate so you can do:
String startDate1 = "2017-03-23";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd");
LocalDate date = LocalDate.parse(startDate1, formatter);
java.sql.Date sqlDate = java.sql.Date.valueOf(date);
As far as I can see, you have a text in yyyy-MM-dd format and you want it in uuuu-MM-dd format. So you need two formats:
String startDate2="2017-03-24";
SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat targetFormat = new SimpleDateFormat("uuuu-MM-dd");
java.sql.Date date = new java.sql.Date(sourceFormat.parse(startDate2).getTime());
String formattedAsDayOfWeek = targetFormat.format(date);
System.out.println(formattedAsDayOfWeek);
Bottom line is that Date contains a millisecond value. java.sql.Date.toString() uses the yyyy-MM-dd format regardless how you parsed it. java.util.sql.Date uses another format: EEE MMM dd hh:mm:ss zzz yyyy with English Locale.
You can do other formatting with DateFormat -s.
I presume you need the uuuu-MM-dd format for inserting data to the database. What does that logic look like?
You don’t want a java.sql.Date. You want a LocalDate. Your SQL database wants one too.
String startDate2 = "2017-03-24";
LocalDate date = LocalDate.parse(startDate2);
System.out.println(date);
Output is:
2017-03-24
I am exploiting the fact that your string is in ISO 8601 format. The classes of java.time including LocalDate parse this format as their default, that is, without any explicit formatter.
You also note that we don’t need any explicit formatter for formatting back into uuuu-MM-dd format for the output. The toString method implicitly called from System..out.println() produces ISO 8601 format back.
Assuming that you are using a JDBC 4.2 compliant driver (I think we all are now), I am taking the way to pass it on to your SQL database from this question: Insert & fetch java.time.LocalDate objects to/from an SQL database such as H2:
myPreparedStatement.setObject ( 1 , date ); // Automatic detection and conversion of data type.
Refer to the linked question for much more detail.
The java.sql.Date class is poorly designed, a true hack on top of the already poorly designed java.util.Date class. Both classes are long outdated. Don’t use any of them anymore.
One more link: Wikipedia article: ISO 8601
I have read a bunch of posts on this, but, I am obviously missing something. I have date string, and a time zone. I am trying to instantiate a date object as follows:
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
java.util.Date dateObj = sdf.parse("2013-10-06 13:30:00");
System.out.println(dateObj);
What is printed is:
Sun Oct 06 09:30:00 EDT 2013
What I want is a date object in UTC format. Not one converted to EDT. What am I doing wrong?
Thanks.
This is because a Date object does not store any timezone information. Date basically only stores the number of milliseconds since the epoch (Jan. 1, 1970). By default Date will use the timezone associated with the JVM. In order to preserve timezone information you should continue using the DateFormat object that you've already got.
See DateFormat#format(Date): http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#format(java.util.Date)
The following should give you what you're looking for:
System.out.println(sdf.format(dateObj));
Try below code, you'll see that the date parsed 1st time is different from the one parsed after setting timezone. Actually the date is parsed as expected in right timezone. It s while printing it gives you get the machines's default TZ.
You could have printed the dateObj.toGMTString() to check the same, but that is deprecated.
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dateObj = sdf.parse("2013-10-06 13:30:00");
System.out.println(dateObj.toString());
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
dateObj = sdf.parse("2013-10-06 13:30:00");
System.out.println(dateObj.toString());
I am doing some XML parsing with SAX
Some elements look like this:
<show time="2014-07-05 20:00:00" />
I need to get a Timestamp out of above String.
Furthermore I also need to get a java.sql.Date, which of course should ignore the exact time.
I saw that there is a Timestamp.parse(String s) method available, but it is deprecated.
Therefore I wanted to ask what is the best Method to get a Timestamp out of this string, and a sql Date out of the Timestamp or String.
Thanks in advance
Edit:
I by the way still have to use Java 1.7 for this project
java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date date = dateFormat.parse("2014-07-05 20:00:00");
java.sql.Timestamp timestamp = new java.sql.Timestamp(date.getTime());
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
I have bunch of dates in a format like Jan. 14,2014,Apr. 20,2014,Aug. 14,2014 etc,. which are extracted from a set of PDF documents.
My Problem
I added the above dates to a mysql column with Column Datatype as Date using java (by PreparedStatement).
....
st.SetDate(3,"Jan. 14,2014");
....
I added the datas using ExecuteQuery.
But when program executes an error message returned by MySql stating that the date formats are incompatible with MySql column type) Date..
My Question
How to convert this above mentioned date formats into mysql compatible Date formats ?
By your current posted code:
st.SetDate(3,"Jan. 14,2014");
This does not even compile. You could try getting a new Date object from a String (since this is what you're trying to accomplish), so use a SimpleDateFormat for this:
SimpleDateFormat sdf = new SimpleDateFormat("MMM. dd,yyyy");
Date date = sdf.parse("Jan. 14,2014");
st.setDate(3, new java.sql.Date(date.getTime()));
//rest of your code...
Similar to this, you can parse time or date and time into a java.util.Date using SimpleDateFormat and then convert it to the respective class java.sql.Time and java.sql.Timestamp using date.getTime().
Also note that you can p̶a̶s̶s̶ retrieve a java.util.Date object reference to PreparedStatement#getDate (and getTime and getTimestamp) since java.sql.Date, java.sql.Time and java.sql.Timestamp extend from java.util.Date. For more info, please refer here: Date vs TimeStamp vs calendar?
Assuming the column type supports a Date value, you could use a SimpleDateFormat to parse the String values to a java.util.Date and create a java.sql.Date which can be applied to the setDate method...
SimpleDateFormat sdf = new SimpleDateFormat("MMM. dd,yyyy");
Date date = sdf.parse("Jan. 14,2014");
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
Check it SimpleDateFormat for more details
One possible solution is to use the String datatype instead of date in your table.
Use SimpleDateFormat to get the string representation of the date to a Date Object.
This date object can then be used to feed the set date method of the prepared statement.
SimpleDateFormat sdf = new SimpleDateFormat(....)
java.util.Date date = sdf.parse(....);
preparedStmt.setDate(...., date);
first convert the java.util.Date to java.sql.Date then try to set the Java.sql.Date
you can use this logic to convert
If your date is String then first convert it into Java.util.Date type either by using the SimpleDateFormat or DateFormat
If u want to use a DateFormat you can use it also:
But this changes the expected date format depending on the locale settings of the machine it's running on.
If you have a specific date format, you can use SimpleDateFormat:
Date d = new SimpleDateFormat("MMM. dd,yyyy").parse("Jan. 14,2014");
java.sql.Date sqlDate = new java.sql.Date(d.getTime());
I don't really think this all java stuff is necessary. You can simply use this very easy sql process to insert date: NOW() in mysql query like INSERT INTO table_name(c1,c2,datecolumn) VALUES('value1','value2',NOW()); It is much simplier I think :D
so i have a mssql database with a DateObjectCreated column of type DateTime. The values it will accept into the table are in the format 2013-12-23 12:23:56.567. However, my java program is creating a joda DateTime object with the format 2013-12-23T 12:23:56.567Z. this wont insert into my db. i need to either convert "2013-12-23T 12:23:56.567Z" to 2013-12-23 12:23:56.567 or find a way to allow my db table to accept "2013-12-23T 12:23:56.567Z" format
any help on this matter will be much appreciated
Many thanks
Billy
Controller
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String formattedDate = formatter.format(date);//this gives me the string as i need it
DateTime dt = new DateTime(formattedDate);//here it adds the 'T' and 'Z'
ive tried
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String formattedDate = formatter.format(date);//this gives me the string as i need it
Date dt = formatter.parse(formattedDate);//here it gives me the same as new Date()
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date myDate = formatter.parse(date);
2.enter link description here
The TO_DATE function can be used in Oracle/PLSQL. For example:
TO_DATE('2003/07/09', 'yyyy/mm/dd') would return a date value of July 9, 2003
TO_DATE('070903', 'MMDDYY') would return a date value of July 9, 2003
TO_DATE('20020315', 'yyyymmdd') would return a date value of Mar 15, 2002
Your DB column has a DateTime type. The text representation of your date is irrelevant for persisting it.
Regardless of the API you are using (JDBC, JPA, Hibernate) there will be something like a "setDateTime(Date date)" method that allows you to pass in a java.util.Date or java.sql.Date or a Java long. You can use the milli-second value of your Joda DateTime object to create whatever is required by the API.
You are working way too hard.
Convert your Joda-Time DateTime object to a java.util.Date. Just call toDate() method.
Pass Date instance to your framework or SQL.
The answer by Ralf is correct in its first part, but is wrong in the end in that you need not deal with milliseconds. Joda-Time knows how to convert to java.util.Date.
org.joda.time.DateTime now = new org.joda.time.DateTime();
java.util.Date nowAsJavaUtilDate = now.toDate();
By the way, the java.sql.Date class is simply a very thin subclass of java.util.Date. So don't let that throw you.
In the future, this will become even easier. Java 8 brings the new JSR 310 classes in the java.time.* package. These classes supplant the mess that is java.util.Date/Calendar. They are inspired by Joda-Time but are entirely re-architected. As they are a built-in part of Java, expect JDBC and related frameworks to be updated to handle these new types directly.