Results 1 to 12 of 12

Thread: Format date

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

    Default Format date

    Hi, i am trying to format date. User can input ANY format of date from a textfield, then from that input I would like to format it in an specific format.

    Error Message: Unparseable date <user input>

    this is what I tried.
    Java Code:
            import java.awt.*;
            import java.awt.event.*;
            import java.text.*;
            import javax.swing.*;
            import java.util.*;
    
            public class AnyFormatOfDate extends JFrame implements ActionListener
            {   private JPanel p;
                private JTextField input, output, format;
                private JButton btnConvert;
    
                public AnyFormatOfDate()
                {   p = new JPanel();
                    p.setPreferredSize(new Dimension( 100,120 ));
                    input = new JTextField("09/26/2010");
                    input.setPreferredSize(new Dimension( 100,25 ));
    
                    format = new JTextField("yyyy-MM-dd");
                    format.setPreferredSize(new Dimension( 100,25 ));
    
                    output = new JTextField();
                    output.setPreferredSize(new Dimension( 100,25 ));
    
                    btnConvert = new JButton("Convert");
                    btnConvert.setPreferredSize(new Dimension( 100,20 ));
                    btnConvert.addActionListener(this);
    
                    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
                    this.setLayout(new BorderLayout());
                    this.add(p, BorderLayout.CENTER);
    
                    p.setLayout(new FlowLayout());
                    p.add(input);
                    p.add(format);
                    p.add(btnConvert);
                    p.add(output);
    
                    pack();
                }
    
                public void actionPerformed(ActionEvent ae)
                {   formatDate(input.getText(), format.getText());
                    System.out.println("STRING TO DATE: " + StringToDate(input.getText()));
    
                }
    
                public static void main(String[] args)
                {   new AnyFormatOfDate().setVisible(true);
                }
    
                private void formatDate(String toFormat, String newFormat)
                {   SimpleDateFormat stringHolder = new SimpleDateFormat();
                    SimpleDateFormat formatter = new SimpleDateFormat(newFormat); //new format of date
    
                    Date date;
                    String formatted_date;
                    try
                    {   date = stringHolder.parse(toFormat);   //convert input in date
                        //formatted_date = formatter.format(date);
                        formatted_date = date.toString();
                    }
                    catch(Exception ex)
                    {   ex.printStackTrace();
                        formatted_date = "error";
                    }
    
                    output.setText(formatted_date);
                }
    
                public static Date StringToDate(String valueToConvert)
                {   SimpleDateFormat converter = new SimpleDateFormat();
                    Date convertedDate;
                    try
                    {convertedDate = converter.parse(valueToConvert);}
                    catch(Exception ex)
                    {   ex.printStackTrace();
                        convertedDate = null;
                    }
                    return convertedDate;
    
                }//end of cmbSelectInput
            }
    thanks,
    geje

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

    Default

    What's the full exception, preferably with stack trace, and where is it thrown from?

    On top of that, what do you mean by "User can input ANY format of date from a textfield"? Do they tell you what format they have enetered? If not then how are you supposed to know what format they have used?

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

    Default

    What's the full exception, preferably with stack trace, and where is it thrown from?
    Java Code:
    java.text.ParseException: Unparseable date: "09/26/2010"
            at java.text.DateFormat.parse(DateFormat.java:337)
            at anyformatofdate.AnyFormatOfDate.formatDate(AnyFormatOfDate.java:65)
            at anyformatofdate.AnyFormatOfDate.actionPerformed(AnyFormatOfDate.java:49)
            at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
            at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
            at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
            at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
            at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
            at java.awt.Component.processMouseEvent(Component.java:6263)
            at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
            at java.awt.Component.processEvent(Component.java:6028)
            at java.awt.Container.processEvent(Container.java:2041)
            at java.awt.Component.dispatchEventImpl(Component.java:4630)
            at java.awt.Container.dispatchEventImpl(Container.java:2099)
            at java.awt.Component.dispatchEvent(Component.java:4460)
            at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4574)
            at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
            at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
            at java.awt.Container.dispatchEventImpl(Container.java:2085)
            at java.awt.Window.dispatchEventImpl(Window.java:2478)
            at java.awt.Component.dispatchEvent(Component.java:4460)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
    it is thrown from
    Java Code:
        private void formatDate(String toFormat, String newFormat)
        {   SimpleDateFormat stringHolder = new SimpleDateFormat();
            SimpleDateFormat formatter = new SimpleDateFormat(newFormat); //new format of date
    
            Date date;
            String formatted_date;
            try
            {   [b]date = stringHolder.parse(toFormat);[/b]   //convert input in date
                //formatted_date = formatter.format(date);
                formatted_date = date.toString();
            }
            catch(Exception ex)
            {   ex.printStackTrace();
                formatted_date = "error";
            }
    
            output.setText(formatted_date);
        }
    On top of that, what do you mean by "User can input ANY format of date from a textfield"? Do they tell you what format they have enetered? If not then how are you supposed to know what format they have used?
    User can input:
    09/26/2010
    26/09/2010
    2010/26/09
    09-26-2010
    26-09-2010
    2010-26-09

    So i have to know what format they use and format it like 09/26/2010.

    I am trying to covert string to date using a SimpleDateFormat without an specified pattern.
    Java Code:
     SimpleDateFormat stringHolder = new SimpleDateFormat();
     Date date;
    
     ...
    
     date = stringHolder.parse(toFormat));  //toFormat is a String that holds the value of input JTextField

    Then format the date using another SimpleDateFormat.
    Java Code:
     SimpleDateFormat formatter = new SimpleDateFormat(newFormat);
     String formatted_Date;
     ....
     formatted_Date = formatter.format(date);

    But I think parsing the string to date using a SimpleDateFormat without an specified pattern an error.

    Thanks,
    geje

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,390
    Rep Power
    25

    Default

    Perhaps you could use some regular expressions to guess what format it might be and then use a SimpleDateFormat setup to parse it.
    If there was more than one, have a chain of SimpleDateFormats with try{}catch blocks to try them one after the other until one succeeds.

  5. #5
    collin389 is offline Senior Member
    Join Date
    Nov 2009
    Posts
    235
    Rep Power
    5

    Default

    Yeah, but Norm, if the user enters 03/09/2010 how are you supposed to know whether it is March 9th or September 3rd? Because the OP said both are viable formats.

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,390
    Rep Power
    25

    Default

    You're right there would be No way to know. The GUI would have to have a checkbox to specify DD/MM or MM/DD for those cases.

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

    Default

    I try it and I was able to figure out waht is the format used. I thought there is a method in SimpleDateFormat the will figure the kind of format.
    Java Code:
        public static String whatIsTheFormat(String valueToFormat)
        {   //possible date formats
            String[] dateFormats = {"", "MM/dd/yyyy", "M/d/yyyy", "dd/MM/yyyy", "d/M/yyyy",
                                 "yyyy/MM/dd", "yyyy/M/d", "yyyy/dd/MM", "yyyy/d/M", ""};
            Boolean formatFound = false;
            int count = 0;
    
            SimpleDateFormat formatter = new SimpleDateFormat();
    
            Date convertedDate;
    
            do
            {   count += 1;
                if(count < 8)
                {   formatter.applyPattern(dateFormats[count]);
    
                    try
                    {   convertedDate = formatter.parse(valueToFormat);
                        formatFound = true;
                    }
                    catch(Exception ex)
                    {   ex.printStackTrace();
                        formatFound = false;
                    }
    
                }
                else {formatFound = true;}
                System.out.println(dateFormats[count]);
            }
            while(formatFound == false);
            System.out.println("FINAL:" + dateFormats[count]);
            return dateFormats[count];
    
        }
    It is working now.
    Thanks,
    geje

  8. #8
    collin389 is offline Senior Member
    Join Date
    Nov 2009
    Posts
    235
    Rep Power
    5

    Default

    Fine, but like I said before, there is no way to differentiate between MM/dd/yyy and dd/MM/yyyy so according to your program whichever comes first is fine and since MM/dd/yyyy comes first, it will format it to that. So when the date is 30/10/2010, then the program will say that it is format: MM/dd/yyyy even though it is not.

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

    Default

    Yep.
    As said, it is impossible to parse a date if you don't know the format beforehand.

    You may think it's working, but I'd bet it isn't.

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

    Default

    collin389
    Fine, but like I said before, there is no way to differentiate between MM/dd/yyy and dd/MM/yyyy so according to your program whichever comes first is fine and since MM/dd/yyyy comes first, it will format it to that. So when the date is 30/10/2010, then the program will say that it is format: MM/dd/yyyy even though it is not.

    Tolls
    Yep.
    As said, it is impossible to parse a date if you don't know the format beforehand.

    You may think it's working, but I'd bet it isn't.
    If that's the case then how can you restrict the user to input just a MM/dd/yyyy format if parse cannot check that the input is invalid?

    I write a small program that check if the user input a valid date or not. But as you guys said this wont check the input 30/10/2010 if this is valid or not, instead the computer will format it and the output will be 06/10/2010.
    Java Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.text.*;
    
    
    public class RestrictedDate extends JFrame
    {	private JTextField input;
    	private JButton checkIfValid;
    	public RestrictedDate()
    	{	this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    		this.setLayout(new FlowLayout());
    
    		input = new JTextField("30/10/2010");
    		input.setPreferredSize(new Dimension( 80, 25 ));
    		this.add(input);
    
    		checkIfValid = new JButton("CLICK");
    		checkIfValid.setPreferredSize(new Dimension( 50, 25 ));
    		checkIfValid.addActionListener(new ActionListener()
    		{	public void actionPerformed(ActionEvent ae)
    			{	Date aDate;
    				SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    				try
    				{	aDate = sdf.parse(input.getText());
    					System.out.println(sdf.format(aDate));
    				}
    				catch(Exception e)
    				{	System.out.println("Invalid Date");
    					e.printStackTrace();
    				}
    			}
    		});
    		this.add(checkIfValid);
    
    		pack();
    	}
    	public static void main(String[] arg)
    	{	new RestrictedDate().setVisible(true);
    	}
    }

    Thanks for helping me to make this thing work real
    geje

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

    Default

    Usually you simply don't let the user input it.
    You'd use a calendar widget, from which they select the date they want.
    Or a series of drop downs (day, month, year).
    Or three text fields (day, month year) and some simple validation.
    Anything other than a simple free text field.

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

    Default

    Ok, there is no way to format dates without knowing the kind of format if the input.
    THanks,
    geje

Similar Threads

  1. Date format exception
    By chaudhas in forum New To Java
    Replies: 7
    Last Post: 06-25-2010, 09:31 AM
  2. julian date to full date format
    By judy318 in forum New To Java
    Replies: 7
    Last Post: 11-02-2009, 12:17 PM
  3. Date Format
    By learnspring in forum New To Java
    Replies: 1
    Last Post: 11-16-2008, 05:16 PM
  4. how to convert date format
    By saran123 in forum New To Java
    Replies: 5
    Last Post: 10-16-2008, 06:10 PM
  5. How to format the date in particular pattern
    By JavaBean in forum Java Tip
    Replies: 0
    Last Post: 10-04-2007, 09:28 PM

Posting Permissions

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