Illegal pattern character 'T' when parsing a date string to java.util.Date

后端 未结 3 467
野性不改
野性不改 2020-11-22 10:03

I have a date string and I want to parse it to normal date use the java Date API,the following is my code:

public static void main(String[] args) {
    Strin         


        
3条回答
  •  臣服心动
    2020-11-22 10:19

    There are two answers above up-to-now and they are both long (and tl;dr too short IMHO), so I write summary from my experience starting to use new java.time library (applicable as noted in other answers to Java version 8+). ISO 8601 sets standard way to write dates: YYYY-MM-DD so the format of date-time is only as below (could be 0, 3, 6 or 9 digits for milliseconds) and no formatting string necessary:

    import java.time.Instant;
    public static void main(String[] args) {
        String date="2010-10-02T12:23:23Z";
        try {
            Instant myDate = Instant.parse(date);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    

    I did not need it, but as getting year is in code from the question, then:
    it is trickier, cannot be done from Instant directly, can be done via Calendar in way of questions Get integer value of the current year in Java and Converting java.time to Calendar but IMHO as format is fixed substring is more simple to use:

    myDate.toString().substring(0,4);
    

提交回复
热议问题