How to get a Date object from String

前端 未结 5 1323
被撕碎了的回忆
被撕碎了的回忆 2021-01-13 06:03
DateFormat formatter = new SimpleDateFormat(\"MM/dd/yyyy\' \'HH:mm:ss\");
Date d = (Date)formatter.parse(dateTime);
System.out.println(\"date in controller \"+d);


        
相关标签:
5条回答
  • 2021-01-13 06:32
    SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:ss");
    System.out.println("date in controller"+ df.format(d));
    
    0 讨论(0)
  • 2021-01-13 06:33

    Don't see why the single-qoutes (') are used in the format-string and you also need to catch ParseException:

    DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
    Date d = new Date();
    try {
        d = (Date)formatter.parse("12/31/2012 12:13:14");
    } catch(ParseException pex) { System.out.println(pex.getMessage()); }
    // convert the date into java.sql.Date
    java.sql.Date sqldate = new java.sql.Date(d.getTime());
    // then put it in the database, something like this:
    //resultSet.updateDate("myDateTimeField", sqldate);
    
    0 讨论(0)
  • 2021-01-13 06:45

    Try using format instead of parse.

    Date date = new Date();
    String DATE_FORMAT = "MM/dd/yyyy";      
    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);        
    System.out.println("Today is " + sdf.format(date) );
    
    0 讨论(0)
  • 2021-01-13 06:52
    Need the output in date format and not as string so as to store the output in datetime field in mysql db
    

    After the statement

    Date d = (Date)formatter.parse(dateTime);
    java.sql.Date sqldate = new java.sql.Date(d.getTime())
    

    you have got a java.util.Date object and you can store it as it is in mysql DB (column type : datetime).

    However, when you are printing d, it defaults to the .toString() implementation. I think you expected some output like Date@ but the toString printed in user readable format thats why the confusion.

    0 讨论(0)
  • 2021-01-13 06:55

    You are using d an object of Date class, so its toString method is called that gives the output as Mon Dec 31 16:04:57 IST 2012.

    If you want to display it in the format that you have specified in your SimpleDateFormat then try using this :

    DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:ss");
    Date d = (Date)formatter.parse(dateTime);
    System.out.println("date in controller "+ formatter.format(d));
    
    0 讨论(0)
提交回复
热议问题