Results 1 to 16 of 16
Thread: JTextField and SimpleDateFormat
- 07-01-2010, 09:01 AM #1
Senior Member
- Join Date
- Apr 2010
- Location
- Philippines
- Posts
- 580
- Rep Power
- 4
JTextField and SimpleDateFormat
hi, i have a JtextField which user can input date in m/d/yyyy format. In mysql date data types are in yyyy-mm-dd format. So i have to change JTextfield's value when user click "add" button. My problem is I cannot format the JTextfield it returns error
Java Code:java.lang.IllegalArgumentException: Cannot format given Object as a Date
here is the sample code that returns the error:
Thanks,Java Code://[b]INPUT:[/b] 5/25/2010 //[b]EXPECTED OUTPUT:[/b] 2010-05-25 import javax.swing.*; import javax.swing.event.*; import java.awt.event.*; import java.awt.*; import java.text.*; public class TextDate extends JFrame { JTextField input = new JTextField(); JTextField output = new JTextField(); JPanel p1 = new JPanel(); JButton b1 = new JButton("CLICK"); public TextDate() { this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setLayout(new BorderLayout()); this.add(p1, BorderLayout.CENTER); p1.setLayout(new GridLayout(2,2)); p1.add(input); p1.add(b1); p1.add(output); pack(); b1.addActionListener(new ButtonClick()); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new TextDate().setVisible(true); } }); } protected class ButtonClick implements ActionListener { public void actionPerformed(ActionEvent ae) { SimpleDateFormat formatdate = new SimpleDateFormat("yyyy-mm-dd"); String newdate = formatdate.format(input.getText()); [b]//error here[/b] output.setText(newdate); } } }
gejeLast edited by mine0926; 07-01-2010 at 09:10 AM.
- 07-01-2010, 01:03 PM #2
Please copy and paste full text of error message here.it returns error
-
You need to use a SDF object to parse the String in the JTextField into a Date object, not a String. Then this Date object can be formatted into the other String using another SDF object.
- 07-01-2010, 04:54 PM #4
Moderator
- Join Date
- Apr 2009
- Posts
- 10,438
- Rep Power
- 16
Wrong. DATE fields in a db do not have a "format" as such. They will display in a stock format (often dependent on the locale setting for the db) but the value stored is not in any way formatted.
So, what you want to do is take the String from the text field, use an SDF to format it into a Date (as suggested above), and then that Date is given to whatever PreparedStatement you are using to INSERT into the db.
Now, this doesn't solve your immediate problem...which is caused by you format()-ting (which is used to go from a Date to a String) rather than parse()-ing (which goes from a String to a Date).
Also, your format is wrong. You have "yyyy-mm-dd" when your input is apparently "5/25/2010", which will fail in any case.
ETA: In fact it's even more convoluted in that you seem to have actually completed missed the String->Date step and decided to go String->String.
- 07-02-2010, 05:04 AM #5
Senior Member
- Join Date
- Apr 2010
- Location
- Philippines
- Posts
- 580
- Rep Power
- 4
The value stored in db does not have format, YES I agree. What I mean is when I use INSERT INTO statement. I try to use insert into in MySql Command Line, not from java, but when I try to insert in date data types using other format it returns error. I use formats like '05/25/2010', '25/05/2010', '2010/05/25'.Wrong. DATE fields in a db do not have a "format" as such. They will display in a stock format (often dependent on the locale setting for the db) but the value stored is not in any way formatted.
Java Code:[i]Error message from MySql Command Line[/i] Incorrect date value: '05-25-2010' for column 'Date_Req' at row 1
Obviously, I do not know this. I think my past coding in other language affect my thinking with this. :)Also, your format is wrong. You have "yyyy-mm-dd" when your input is apparently "5/25/2010", which will fail in any case.
Can you explain why it will fail? Because that is actually what I am trying to do here. User can enter date in any format but in insert into it should be format to 'yyyy-mm-dd'
I dont fully understand it but I try it. Its working but I dont know if this is what you mean...You need to use a SDF object to parse the String in the JTextField into a Date object, not a String. Then this Date object can be formatted into the other String using another SDF object.
problem now is it gives different output.Java Code:import javax.swing.*; import javax.swing.event.*; import java.awt.event.*; import java.awt.*; import java.text.*; public class TextDate extends JFrame { JTextField input = new JTextField(); JTextField output = new JTextField(); JPanel p1 = new JPanel(); JButton b1 = new JButton("CLICK"); public TextDate() { this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setLayout(new BorderLayout()); this.add(p1, BorderLayout.CENTER); p1.setLayout(new GridLayout(2,2)); p1.add(input); p1.add(b1); p1.add(output); pack(); b1.addActionListener(new ButtonClick()); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new TextDate().setVisible(true); } }); } protected class ButtonClick implements ActionListener { public void actionPerformed(ActionEvent ae) { String strDate = null; try {//before I use yyyy-mm-dd, base from [url="http://www.kodejava.org/examples/19.html"]other site[/url] Small "m" means minute and not month. DateFormat mySqlFormat = new SimpleDateFormat[b]("yyyy-MM-dd")[/b]; java.util.Date newDate = (java.util.Date)mySqlFormat.parse(input.getText()); System.out.println("input TextField:" + input.getText()); System.out.println("newDate value :" + newDate); strDate = mySqlFormat.format(newDate).toString(); } catch(Exception ex){ex.printStackTrace();} output.setText(strDate); System.out.println("output TextField:" + input.getText()); } } }
Thanks,Java Code:input: -----------> 05-15-2010 output: ----------> 0011-08-31 newDate output: --> Mon Aug 31 00:00:00 CST 11
gejeLast edited by mine0926; 07-02-2010 at 05:06 AM.
- 07-02-2010, 09:09 AM #6
Moderator
- Join Date
- Apr 2009
- Posts
- 10,438
- Rep Power
- 16
OK, but normally you would use a to_date() function to convert the String into a date. I expect MySQL has similar ones to Oracle. In fact, a quick Google and it's called Str_To_Date, which does pretty much what a SimpleDateFormat does. Forcing the database to do the translation itself is generally not good practice.
Anyway, since you will be using JDBC this isn't important. With a JDBC PreparedStatement you have setters for each datatype, one of which is setDate, which accepts a Date object. That's what you want to use.
OK, SimpleDateFormat has a format string. That string defines the format of the string you are working with, whether the string you are turning a Date into (format()), or the String you are using to create a Date (parse()). If you parse() a String with a different format you will get an exception (FormatException?) because the String, in this case "5/25/2010", does not match the format given to the SimpleDateFormat, in this case "yyyy-mm-dd".
OK, look at your input. You have month, day, year. Look at your format, you have year, month, day. Since the SimpleDateFormat defaults to lenient it attempts to format something that vaguely matches, so it's taken '05' as your year, '15' as your month (so rolls that into '06'), and '2010' as your day, so runs that forward several years until it hits a valid date.
Then you print out the resulting Date. Note I said above that Dates do not have a format, whether a Date object or a DATE field in a database. So all that printout is is the default Date format.
Anyway, you do NOT need to do anything other than parse from the input text to get a Date. You do NOT need to then format that date. Just use the Date object in your PreparedStatement.
- 07-03-2010, 04:08 AM #7
Senior Member
- Join Date
- Apr 2010
- Location
- Philippines
- Posts
- 580
- Rep Power
- 4
heres what it try..Anyway, you do NOT need to do anything other than parse from the input text to get a Date. You do NOT need to then format that date. Just use the Date object in your PreparedStatement.
I think parse() return java.util.Date while setDate() requires java.sql.Date thats why it return that error messageJava Code:protected class ButtonClick implements ActionListener { public void actionPerformed(ActionEvent ae) { String strDate = null; Date newDate = null; //java.sql.Date try { DateFormat mySqlFormat = new SimpleDateFormat("yyyy-M-d"); newDate = (Date)mySqlFormat.parse(txtReqDate.getText()); System.out.println("input TextField:" + input.getText()); System.out.println("newDate value :" + newDate.toString()); } catch(Exception ex){ex.printStackTrace();} output.setText(newDate.toString()); System.out.println("output TextField:" + output.getText()); } } [b]ERROR MESSAGE[/b] java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Date
Still cant get it..
I try to change newDate from java.sql.Date to java.util.Date. But netbeans giving me Error message
Java Code:[b]CODE[/b] java.util.Date newDate = null; [b]ERROR MESSAGE[/b] //netbeans underline the newDate (From setDate(2, newDate)) cannot find symbol symbol: method setDate(int, java.util.Date) location: interface java.sql.PreparedStatement
Thanks for your time and for helping me,
geje
-
I don't do SQL, but I do know that the SimpleDateFormate class parses a String into a java.util.Date object not a java.sql.Date, and casting won't change this fact. Perhaps you can use this java.util.Date object in your prepared statement, but I don't know.
- 07-03-2010, 04:41 AM #9
Senior Member
- Join Date
- Apr 2010
- Location
- Philippines
- Posts
- 580
- Rep Power
- 4
Have done that. At post#7 on my second try. I change newDate from java.sql.Date to java.util.Date
from source window in netbeans, newDate is undelined.Java Code:java.util.Date newDate = null; try { DateFormat mySqlFormat = new SimpleDateFormat("yyyy-MM-dd"); newDate = mySqlFormat.parse(input.getText()); } catch(Exception ex){ex.printStackTrace();} try {//PreparedStatement here ... prep_stmt.setDate(2, newDate); //<-- newDate is the only underlined. When I point my cursor to new date it gives the error message [b]ERROR MESSAGE[/b] cannot find symbol symbol: method setDate(int, java.util.Date) location: interface java.sql.PreparedStatement } catch(Exception ex){ex.printStackTrace();}
-
Again, I'm speaking out of ignorance, but can you change a java.util.Date to a java.sql.Date via the latter's constructor?:
Java Code:java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
- 07-03-2010, 05:41 AM #11
Senior Member
- Join Date
- Apr 2010
- Location
- Philippines
- Posts
- 580
- Rep Power
- 4
Thanks. I was able to insert the new record. Here is what I did.
Java Code:java.sql.Date newDate = null; //java.sql.Date try { DateFormat mySqlFormat = new SimpleDateFormat("yyyy-M-d"); newDate = new java.sql.Date(mySqlFormat.parse(input.getText()).getTime()); } catch(Exception ex){ex.printStackTrace();}
I also saw an example from this site.. I think what I am trying to do is same with this one but they use valueof().
But both code requires me to enter "yyyy-mm-dd" format because They assume that substring BEFORE first dash("-") character is year, substring AFTER first dash("-") character and BEFORE SECODE dash("-") is month, substring AFTER SECOND dash is day.
THIS IS FROM Date.java from java.sql package
You think I have to create a class that will format a date or string into desire format? Just like JFormattedTextField?Java Code:public static Date valueOf(String s) { final int YEAR_LENGTH = 4; final int MONTH_LENGTH = 2; final int DAY_LENGTH = 2; final int MAX_MONTH = 12; final int MAX_DAY = 31; int firstDash; int secondDash; Date d = null; if (s == null) { throw new java.lang.IllegalArgumentException(); } firstDash = s.indexOf('-'); secondDash = s.indexOf('-', firstDash + 1); if ((firstDash > 0) && (secondDash > 0) && (secondDash < s.length()-1)) {[b] String yyyy = s.substring(0, firstDash); String mm = s.substring(firstDash + 1, secondDash); String dd = s.substring(secondDash + 1);[/b] if (yyyy.length() == YEAR_LENGTH && mm.length() == MONTH_LENGTH && dd.length() == DAY_LENGTH) { int year = Integer.parseInt(yyyy); int month = Integer.parseInt(mm); int day = Integer.parseInt(dd); if (month >= 1 && month <= MAX_MONTH) { int maxDays = MAX_DAY; switch (month) { // February determine if a leap year or not case 2: if((year % 4 == 0 && !(year % 100 == 0)) || (year % 400 == 0)) { maxDays = MAX_DAY-2; // leap year so 29 days in February } else { maxDays = MAX_DAY-3; // not a leap year so 28 days in February } break; // April, June, Sept, Nov 30 day months case 4: case 6: case 9: case 11: maxDays = MAX_DAY-1; break; } if (day >= 1 && day <= maxDays) { d = new Date(year - 1900, month - 1, day); } } } } if (d == null) { throw new java.lang.IllegalArgumentException(); } return d; }
Thanks,
gejeLast edited by mine0926; 07-03-2010 at 06:05 AM.
- 07-05-2010, 09:11 AM #12
Senior Member
- Join Date
- Apr 2010
- Location
- Philippines
- Posts
- 580
- Rep Power
- 4
You think I have to create a class that will format a date or string into desire format? Just like JFormattedTextField?
On user input they want a "M/d/yyyy" while in setDate() method in PreparedStatement it requires "yyyy-M-d"?
Thanls in advance,
geje
- 07-05-2010, 10:18 AM #13
Moderator
- Join Date
- Apr 2009
- Posts
- 10,438
- Rep Power
- 16
OK, I missed the conversion from util.Date to sql.Date, but you have the line for that now:
Now, as I keep saying, Date objects, and the DATE column type, do not have a format!Java Code:newDate = new java.sql.Date(mySqlFormat.parse(input.getText()).getTime());
So you want a SimpleDateFormat of "MM/dd/yyyy" to parse the text field value, which you then turn into a sql.Date (as the line above). You then use that object in the setDate() method of a PreparedStatement.
That's it...nothing else.
- 07-06-2010, 02:02 AM #14
Senior Member
- Join Date
- Apr 2010
- Location
- Philippines
- Posts
- 580
- Rep Power
- 4
OK. Everything works now. After searching for what is wrong I found out that I forgot to change
Many thanks to Fubarable and Tolls.Java Code:SimpleDateFormat("yyyy-MM-dd") to SimpleDateFormat("MM/dd/yyyy").
gejeLast edited by mine0926; 07-06-2010 at 03:06 AM.
-
You're welcome and glad you've got things working. Please let us know how this project eventually turns out.
- 07-06-2010, 03:10 AM #16
Senior Member
- Join Date
- Apr 2010
- Location
- Philippines
- Posts
- 580
- Rep Power
- 4
Similar Threads
-
How to use SimpleDateFormat in J2ME Applications
By thirupathik in forum CDC and Personal ProfileReplies: 9Last Post: 08-13-2010, 08:18 PM -
JFormattedTextField + SimpleDateFormat
By Ralphw in forum AWT / SwingReplies: 1Last Post: 07-07-2009, 10:53 AM -
Locale with SimpleDateFormat
By swati.jyoti in forum New To JavaReplies: 4Last Post: 07-02-2009, 02:34 PM -
how to access jTextField of one JFrame1 from JFrame2 & Modify JTextField contents
By sumit1mca in forum AWT / SwingReplies: 1Last Post: 01-30-2009, 06:44 PM -
Using SimpleDateFormat
By Java Tip in forum Java TipReplies: 1Last Post: 07-18-2008, 08:33 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks