3

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

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Wil Ferraciolli
  • 449
  • 3
  • 9
  • 21
  • What is your output from the sample code? – Jokab Jul 18 '16 at 12:38
  • Why do you have to convert it first? What's wrong with using a different SDF to parse it? – Zircon Jul 18 '16 at 12:38
  • 1
    You just need to parse it with the correct format of your `string` into a date and then format it with `SimpleDateFormat format` into your target format. – Tom Jul 18 '16 at 12:39
  • 1
    read the accepted answer of this http://stackoverflow.com/questions/2597083/illegal-pattern-character-t-when-parsing-a-date-string-to-java-util-date thread you will get you answer. – Saif Jul 18 '16 at 12:45
  • Does this answer your question? [Illegal pattern character 'T' when parsing a date string to java.util.Date](https://stackoverflow.com/questions/2597083/illegal-pattern-character-t-when-parsing-a-date-string-to-java-util-date) – Ian Kemp Jan 23 '23 at 18:55

2 Answers2

10

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();
    }
Arnaud
  • 17,229
  • 3
  • 31
  • 44
-1

try this

DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
   // you can change format of date
  Date date = formatter.parse(strDate);
  Timestamp timeStampDate = new Timestamp(date.getTime());

  return timeStampDate;
bforblack
  • 65
  • 5