Search code examples
javasimpledateformatdate-format

Java SimpleDateFormat not detecting month


I'm using SimpleDateFormat in Java and for some reason it is not detecting the month. Here is my code:

     /**
     * Takes a date/time stamp which looks like yyyyMMDDhhmmss on converts it to
     * yyyy-MM-DDThh:mm:ssZ
     *
     * @param timestamp
     * @return
     */
    public static String ConvertDate(String timestamp) {
        if (timestamp == null || timestamp.length() < 14)
            return null;

        String timeString = null;

        System.out.println(timestamp);
        DateFormat outputFormat = new SimpleDateFormat("YYYY-MM-DD'T'hh:mm:ss'Z'");
        DateFormat inputFormat = new SimpleDateFormat("yyyyMMDDhhmmss");

        try{
            Date date = inputFormat.parse(timestamp);
            timeString = outputFormat.format(date);
        }
        catch(Exception e){}

        return timeString;
    }

Calling this method: ConvertDate("20190803122424") returns the following: 2019-01-03T12:24:24Z whereas I want to return: 2019-08-03T12:24:24Z

Is there something wrong with my output format?


Solution

  • You are using the wrong date format string: DD (day in year) instead of dd (day in month). Change both SimpleDateFormat instance to use dd:

    DateFormat inputFormat = new SimpleDateFormat("yyyyMMddhhmmss");
    DateFormat outputFormat = new SimpleDateFormat("YYYY-MM-dd'T'hh:mm:ss'Z'");
    

    Therefore you are getting the wrong result.