javajodatimesimpledateformatjava.util.date

2020-04-03 20:17:46 to "yyyy-MM-dd'T'HH:mm:ss" format


Is there any way in java(java.util.* or Joda api ) to convert "2020-04-03 20:17:46" to "yyyy-MM-dd'T'HH:mm:ss"

new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
          .parse("2020-04-03 20:17:46")

its giving java.text.parseException always


Solution

  • Just for the case you are using Java 8 or above, make use of java.time.
    See this simple example:

    public static void main(String[] args) {
        // example datetime
        String datetime = "2020-04-03 20:17:46";
        // create a formatter that parses datetimes of this pattern
        DateTimeFormatter parserDtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // then parse the datetime with that formatter
        LocalDateTime ldt = LocalDateTime.parse(datetime, parserDtf);
        // in order to output the parsed datetime, use the default formatter (implicitly)
        System.out.println(ldt);
        // or format it in a totally different way
        System.out.println(ldt.format(
                DateTimeFormatter.ofPattern("EEE, dd. 'of' MMM 'at' hh-mm-ss a",
                        Locale.ENGLISH)
                )
        );
    }
    

    This outputs

    2020-04-03T20:17:46
    Fri, 03. of Apr at 08-17-46 PM
    

    Please note that this doesn't consider any time zone or offset, it just represents a date and time consisting of the passed or parsed years, months, days, hours, minutes and seconds, nothing else.