0

I want to convert the following pattern to yyyy-mm-ddThh:mm:ssz

         2017-feb-02
         2017-05-02
         2017-01-01 03:00:00
         2017-01-01 00:00:00.0

I have gone through SimpleDateFormat class of Java. But I coudn't able to achieve it.

Gibbs
  • 21,904
  • 13
  • 74
  • 138
  • 1
    Hope this one helps [Java string to date conversion](http://stackoverflow.com/questions/4216745/java-string-to-date-conversion) – AimeTPGM Mar 24 '17 at 09:09
  • Have you seen this: http://stackoverflow.com/a/4024604/3042145 And the T Character you need to surround it with '', as GopsAB mentioned – kism3t Mar 24 '17 at 09:20
  • Possible duplicate of [Java string to date conversion](http://stackoverflow.com/questions/4216745/java-string-to-date-conversion) – Tom Mar 24 '17 at 09:24

2 Answers2

1

The pattern you want to convert it should be like: yyyy-MM-dd'T'HH:mm:ssz. See more here. You can do it with SimpleDateFormat, a small example:

    String date = "2017-05-02";
    String oldFormat = "yyyy-MM-dd";
    String newFormat = "yyyy-MM-dd'T'HH:mm:ssz";
    SimpleDateFormat sdf = new SimpleDateFormat(oldFormat);
    try {
        Date newDate = sdf.parse(date);
        sdf.applyPattern(newFormat);
        System.out.println(sdf.format(newDate));
    } catch (ParseException e) {
        e.printStackTrace();
    }
alexandrum
  • 429
  • 9
  • 17
  • Seems interesting. let me try that 'applyPattern'. But how do I solve the other cases. My date string is dynamic. I dont want to have n formats to parse – Gibbs Mar 24 '17 at 09:16
  • @GopsAB, well, you have N formats to parse already, according to your question. Why not have N parsers? These won't make you hard-pressed from memory standpoint or anything. – M. Prokhorov Mar 24 '17 at 09:26
  • @GopsAB, you kind of need to know and have the right or expected formats, else how can you determine which is the month in `2017-05-02` for example? You can easily make an `Enum` with all the formats and use them properly. – alexandrum Mar 24 '17 at 09:31
0

I would solve your problem like this, with the help mentioned in the comment section of your question:

public static void main(final String[] args) throws Exception {

    String[] formatStrings = { "yyyy-MMM-dd", "yyyy-MM-dd", "yyyy-MMM-dd hh:mm:ss", "yyyy-MMM-dd hh:mm:ss.S" };

    String yourDate = "2017-Mar-02";
    Date date = null;
    for (String formatString : formatStrings) {
        try {
            date = new SimpleDateFormat(formatString, Locale.US).parse(yourDate);
        } catch (ParseException e) {
        }
    }
    DateFormat formatTo = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssz", Locale.US);
    System.out.println(formatTo.format(date));
}
kism3t
  • 1,343
  • 1
  • 14
  • 33