Search code examples
javajsondatedate-format

Date Format [ 2020, 9, 15 ]: What type of format is this?


I'm trying to consume external json, which has a few dates. Format for date is: [ 2020, 9, 15 ] I've tried using it as a string but it didn't work.

Can you please tell me what kind of format is this


Solution

  • java.time

    Read the JSON number array into a Java int[] (int array) and construct a LocalDate from it.

        int[] arrayFromJson = { 2020, 9, 15 };
        System.out.println("Array from JSON: " + Arrays.toString(arrayFromJson));
        
        LocalDate date = LocalDate.of(arrayFromJson[0], arrayFromJson[1], arrayFromJson[2]);
        System.out.println("Date as LocalDate: " + date);
    

    Output is:

    Array from JSON: [2020, 9, 15]
    Date as LocalDate: 2020-09-15
    

    LocalDate is the class from java.time, the modern Java date and time API, for representing a date without time of day, so the right class to use here.

    Reading and parsing the JSON

    How to read the JSON into Java? It depends on which library you are using for doing that. Here’s an example using Jackson:

        ObjectMapper mapper = new ObjectMapper();
        String json = "[ 2020, 9, 15]";
    
        int[] arrayFromJson = mapper.readValue(json, int[].class);
        System.out.println(Arrays.toString(arrayFromJson));
    
    [2020, 9, 15]