Results 1 to 16 of 16
  1. #1
    mine0926 is offline Senior Member
    Join Date
    Apr 2010
    Location
    Philippines
    Posts
    580
    Rep Power
    5

    Default 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:
    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);
                        }
                }
        }
    Thanks,
    geje
    Last edited by mine0926; 07-01-2010 at 10:10 AM.

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,816
    Rep Power
    25

    Default

    it returns error
    Please copy and paste full text of error message here.

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    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.

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,183
    Rep Power
    20

    Default

    Quote Originally Posted by mine0926 View Post
    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.
    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.

  5. #5
    mine0926 is offline Senior Member
    Join Date
    Apr 2010
    Location
    Philippines
    Posts
    580
    Rep Power
    5

    Default

    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.
    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'.
    Java Code:
     [i]Error message from MySql Command Line[/i]
     Incorrect date value: '05-25-2010' for column 'Date_Req' at row 1

    Also, your format is wrong. You have "yyyy-mm-dd" when your input is apparently "5/25/2010", which will fail in any case.
    Obviously, I do not know this. I think my past coding in other language affect my thinking with this. :)
    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'


    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.
    I dont fully understand it but I try it. Its working but I dont know if this is what you mean...
    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());
    		}
    	}
    }
    problem now is it gives different output.
    Java Code:
    input: -----------> 05-15-2010
    output: ----------> 0011-08-31
    newDate output: --> Mon Aug 31 00:00:00 CST 11
    Thanks,
    geje
    Last edited by mine0926; 07-02-2010 at 06:06 AM.

  6. #6
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,183
    Rep Power
    20

    Default

    Quote Originally Posted by mine0926 View Post
    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'.
    Java Code:
     [i]Error message from MySql Command Line[/i]
     Incorrect date value: '05-25-2010' for column 'Date_Req' at row 1
    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.

    Quote Originally Posted by mine0926 View Post
    Obviously, I do not know this. I think my past coding in other language affect my thinking with this. :)
    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'
    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".

    Quote Originally Posted by mine0926 View Post
    I dont fully understand it but I try it. Its working but I dont know if this is what you mean...
    Java Code:
    	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());
    		}
    	}
    }
    problem now is it gives different output.
    Java Code:
    input: -----------> 05-15-2010
    output: ----------> 0011-08-31
    newDate output: --> Mon Aug 31 00:00:00 CST 11
    Thanks,
    geje
    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.

  7. #7
    mine0926 is offline Senior Member
    Join Date
    Apr 2010
    Location
    Philippines
    Posts
    580
    Rep Power
    5

    Default

    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.
    heres what it try..
    Java 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
    I think parse() return java.util.Date while setDate() requires java.sql.Date thats why it return that error message


    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

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    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.

  9. #9
    mine0926 is offline Senior Member
    Join Date
    Apr 2010
    Location
    Philippines
    Posts
    580
    Rep Power
    5

    Default

    Have done that. At post#7 on my second try. I change newDate from java.sql.Date to java.util.Date
    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();}
    from source window in netbeans, newDate is undelined.

  10. #10
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    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());

  11. #11
    mine0926 is offline Senior Member
    Join Date
    Apr 2010
    Location
    Philippines
    Posts
    580
    Rep Power
    5

    Default

    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
    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;
        }
    You think I have to create a class that will format a date or string into desire format? Just like JFormattedTextField?

    Thanks,
    geje
    Last edited by mine0926; 07-03-2010 at 07:05 AM.

  12. #12
    mine0926 is offline Senior Member
    Join Date
    Apr 2010
    Location
    Philippines
    Posts
    580
    Rep Power
    5

    Default

    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

  13. #13
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,183
    Rep Power
    20

    Default

    Quote Originally Posted by mine0926 View Post
    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
    OK, I missed the conversion from util.Date to sql.Date, but you have the line for that now:
    Java Code:
    newDate = new java.sql.Date(mySqlFormat.parse(input.getText()).getTime());
    Now, as I keep saying, Date objects, and the DATE column type, do not have a format!

    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.

  14. #14
    mine0926 is offline Senior Member
    Join Date
    Apr 2010
    Location
    Philippines
    Posts
    580
    Rep Power
    5

    Default

    OK. Everything works now. After searching for what is wrong I found out that I forgot to change
    Java Code:
    SimpleDateFormat("yyyy-MM-dd") to SimpleDateFormat("MM/dd/yyyy").
    Many thanks to Fubarable and Tolls.
    geje
    Last edited by mine0926; 07-06-2010 at 04:06 AM.

  15. #15
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    You're welcome and glad you've got things working. Please let us know how this project eventually turns out.

  16. #16
    mine0926 is offline Senior Member
    Join Date
    Apr 2010
    Location
    Philippines
    Posts
    580
    Rep Power
    5

    Default

    Quote Originally Posted by Fubarable View Post
    Please let us know how this project eventually turns out.
    Sorry, Im not good in english. You mean this?
    Java Code:
     	try
            {   DateFormat mySqlFormat = new SimpleDateFormat([b]"M/d/yyyy"[/b]);
                newDate = new java.sql.Date(mySqlFormat.parse(input.getText()).getTime());
            }
            catch(Exception ex){ex.printStackTrace();}

Similar Threads

  1. How to use SimpleDateFormat in J2ME Applications
    By thirupathik in forum CDC and Personal Profile
    Replies: 9
    Last Post: 08-13-2010, 09:18 PM
  2. JFormattedTextField + SimpleDateFormat
    By Ralphw in forum AWT / Swing
    Replies: 1
    Last Post: 07-07-2009, 11:53 AM
  3. Locale with SimpleDateFormat
    By swati.jyoti in forum New To Java
    Replies: 4
    Last Post: 07-02-2009, 03:34 PM
  4. Replies: 1
    Last Post: 01-30-2009, 07:44 PM
  5. Using SimpleDateFormat
    By Java Tip in forum Java Tip
    Replies: 1
    Last Post: 07-18-2008, 09:33 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •