Parsing a Date from a String in Java?

后端 未结 2 668
花落未央
花落未央 2021-01-27 09:21

I\'m trying to parse a String to a Date Object, as part of a loading functionality for my program, as seen below:

    String dateString = \"Wed Jan 18 23:22:18 E         


        
2条回答
  •  不知归路
    2021-01-27 10:02

    The hour should be HH, not hh

    h Hour in am/pm (1-12)

    And year should be yyyy not YYYY

    Y Week year

    ALWAYS consult the JavaDocs first

    String dateString = "Wed Jan 18 23:22:18 EST 2017";
    SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
    try {
        Date scheduleItemDate = sdf.parse(dateString);
        System.out.println(dateString);
        System.out.println(scheduleItemDate.toString());
        System.out.println(sdf.format(scheduleItemDate));
    } catch (ParseException e) {
        System.out.println("Exception");
    }
    

    Which now prints...

    Wed Jan 18 23:22:18 EST 2017
    Wed Jan 18 23:22:18 EST 2017
    Wed Jan 18 23:22:18 EST 2017
    

提交回复
热议问题