Search code examples
javanetbeanssimpledateformatjdatechooser

How to convert one formatted date String to another format


I have a JDateChooser bean panel named basDate. When i execute System.out.println(basDate.getText()); it returns 12.02.2014 But i must convert and edit it to 2014-02-12 00:00:00.000

Just i want edit and assign new output to a variable coming as "12.02.2014" value as "2014-02-12 00:00:00.000"

I use Netbeans Gui Builder.


Solution

  • Since the input date is a string in a different format from what you want, you need to two SimpleDateFormats. One to parse the String to a Date and another to format the Date to a different format.

    Test this out. input 12.02.2014 output 2014-12-02 00:00:00:000

    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    public class MyDateFormat {
    
        public static void main(String[] args){
            String inputStringDate = "12.02.2014";
            SimpleDateFormat inputFormat = new SimpleDateFormat("dd.MM.yyyy");
            Date inputDate = null;
            try {
                inputDate = inputFormat.parse(inputStringDate);
            } catch (ParseException ex) {
                Logger.getLogger(MyDateFormat.class.getName()).log(Level.SEVERE, null, ex);
            }
    
            SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-dd-MM HH:mm:ss:SSS");
            String outputStringDate = outputFormat.format(inputDate);
    
            System.out.println(outputStringDate);      
        }
    }