What is this date format? 2011-08-12T20:17:46.384Z

前端 未结 8 2089
日久生厌
日久生厌 2020-11-22 16:56

I have the following date: 2011-08-12T20:17:46.384Z. What format is this? I\'m trying to parse it with Java 1.4 via DateFormat.getDateInstance().parse(

相关标签:
8条回答
  • 2020-11-22 17:48

    @John-Skeet gave me the clue to fix my own issue around this. As a younger programmer this small issue is easy to miss and hard to diagnose. So Im sharing it in the hopes it will help someone.

    My issue was that I wanted to parse the following string contraining a time stamp from a JSON I have no influence over and put it in more useful variables. But I kept getting errors.

    So given the following (pay attention to the string parameter inside ofPattern();

    String str = "20190927T182730.000Z"
    
    LocalDateTime fin;
    fin = LocalDateTime.parse( str, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss.SSSZ") );
    

    Error:

    Exception in thread "main" java.time.format.DateTimeParseException: Text 
    '20190927T182730.000Z' could not be parsed at index 19
    

    The problem? The Z at the end of the Pattern needs to be wrapped in 'Z' just like the 'T' is. Change "yyyyMMdd'T'HHmmss.SSSZ" to "yyyyMMdd'T'HHmmss.SSS'Z'" and it works.

    Removing the Z from the pattern alltogether also led to errors.

    Frankly, I'd expect a Java class to have anticipated this.

    0 讨论(0)
  • 2020-11-22 17:49

    You can use the following example.

        String date = "2011-08-12T20:17:46.384Z";
    
        String inputPattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
    
        String outputPattern = "yyyy-MM-dd HH:mm:ss";
    
        LocalDateTime inputDate = null;
        String outputDate = null;
    
    
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern(inputPattern, Locale.ENGLISH);
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern(outputPattern, Locale.ENGLISH);
    
        inputDate = LocalDateTime.parse(date, inputFormatter);
        outputDate = outputFormatter.format(inputDate);
    
        System.out.println("inputDate: " + inputDate);
        System.out.println("outputDate: " + outputDate);
    
    0 讨论(0)
提交回复
热议问题