Format Date yyyy-mm-ddTHH:mm:ssZ to dd/MM/yyyy HH:mm

Asked

Viewed 5,419 times

1

I receive in JSON a date field "created_at": "2013-01-08T20:11:48Z" and wanted to present on the screen in the formed of Brazil but I can’t use Simpledateformat to format and present in any way.

2 answers

2

Follows solution below:

String dataJson = "2013-01-08T20:11:48Z".replaceAll("T", " ").replaceAll("Z", "");
SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");

Date dataFormatada = new Date(format.parse(dataJson).getTime());
System.out.println(dataFormatada);

Access here to see the result.

  • The date is now leaving like this: Thu Mar 09 08:14:00 GMT-03:00 ..........

  • On my computer appeared like this: Tue Jan 08 20:11:48 GMT 2013

  • 1

    Check your computer’s UTC configuration

1

Try using the new Java 8 date API this way:

public static void main(String[] args) {
    String data = "2013-01-08T20:11:48Z";
    DateTimeFormatter originalFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
    DateTimeFormatter targetFormat = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");

    // Com isso já da pra fazer várias manipulações interessantes
    LocalDateTime dateTime = LocalDateTime.parse(data, originalFormat);

    // ou assim
    DateTimeFormatter formatador = DateTimeFormatter
        .ofLocalizedDateTime(FormatStyle.MEDIUM)
        .withLocale(new Locale("pt", "br"));

    System.out.println(data);
    System.out.println(dateTime.format(targetFormat));
    System.out.println(dateTime.format(formatador));
}

See working on Ideone.

Other references:

Learn about the new Java 8 Date API

Browser other questions tagged

You are not signed in. Login or sign up in order to post.