convert string to date type

后端 未结 2 1792
再見小時候
再見小時候 2021-01-26 05:24

I want to convert string to date format, but the following way didn\'t work.

It yields null for birth.

2条回答
  •  盖世英雄少女心
    2021-01-26 06:13

    Your answer is right on the money. I put it in a full program and tested it.
    It now prints out

    Default date format Fri Mar 30 00:00:00 CDT 2012
    Our SimpleDateFormat 30-Mar-2012
    Our SimpleDateFormat with all uppercase 30-MAR-2012
    

    Here are some tips:

    • Make sure that you are including the correct imports. Depending on what is in your classpath, you may have accidentally imported java.sql.Date or some other rogue import.
    • Try printing the contents of birthDate before entering the try block and verify that it really contains a string of format dd-MMM-yyyy

    -

    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    public class BirthDate {
    
        public static void main(String[] args) {
            Date birth = null;
            String birthDate = "30-MAR-2012";
            DateFormat formatter = null;
            try {
                formatter = new SimpleDateFormat("dd-MMM-yyyy");
                birth = (Date) formatter.parse(birthDate); // birtDate is a string
            }
            catch (ParseException e) {
                System.out.println("Exception :" + e);
            }
            if (birth == null) {
                System.out.println("Birth object is still null.");
            } else {
                System.out.println("Default date format " + birth);
                System.out.println("Our SimpleDateFormat " + formatter.format(birth));
                System.out.println("Our SimpleDateFormat with all uppercase " + formatter.format(birth).toUpperCase());
            }
        }
    }
    

提交回复
热议问题