Skip to content
Advertisement

How to format date/time string? (Java)

Hi can anyone help please? I am trying to format a date and time string. Currently it looks like this “20160112T110000Z” and I need it to be “2016-01-12T11:00:00Z

The string without the special characters are returned from a 3rd party recurrence library. I need to convert it to have the special characters before parsing it to a Calendar object.

Can anyone help please?

The code that I have so far looks like:

 final String TIMEFORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
 String string = "20160112T110000Z";
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    Date date = format.parse(string);
    System.out.println(date); 

However this just does not work.

Any suggestions are appreciated

Advertisement

Answer

You have to read the string with a format matching the source, this gives you a correct Date.

Then simply write it with the format you want :

    String string = "20160112T110000Z";

    String originalStringFormat = "yyyyMMdd'T'HHmmss'Z'";
    String desiredStringFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'";

    SimpleDateFormat readingFormat = new SimpleDateFormat(originalStringFormat);
    SimpleDateFormat outputFormat = new SimpleDateFormat(desiredStringFormat);

    try {
        Date date = readingFormat.parse(string);
        System.out.println(outputFormat.format(date));
    } catch (ParseException e) {

        e.printStackTrace();
    }
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement