convert string to date type

后端 未结 2 1791
再見小時候
再見小時候 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 05:54

    Your code works fine. If you care to use Joda Time you can use this. You can go through the documentation to unleash the complete functionality in case you plan to use the time for DB testing and stuff.

    import org.joda.time.DateTime;
    DateTime dt = new DateTime("YYYY-MM-DD");//new DateTime("2012-03-30")
    System.out.println(dt);
    
    0 讨论(0)
  • 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());
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题