Formatting date in java

Asked

Viewed 5,377 times

5

I need to format a date that comes for example: 20161109103000 for 2016-11-09 10:30:00.

I’ve tried to use SimpleDateFormat, DateTimeFormatter and I couldn’t format the date.

2 answers

6


Try as below:

String strData = "20161109103000";  
Date dt = new SimpleDateFormat("yyyyMMddHHmmss").parse(strData);
String dataFormatada = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(dt);

Output from the variable dataFormatada:

2016-11-09 10:30:00

This will create a type object util.Date from the string and then convert to the desired format in string, again.

See the result in ideone: https://ideone.com/ZDplvz

  • I think my feed is screwing with me! = D huehue

  • 1

    @white mine showed straight, only I was already with the page of the site open haha

  • 1

    @I cut a lot of dough this ideone. Thank you! :)

2

Using the new API dava.time, with the DateTimeFormatter:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.ResolverStyle;

class Datas {
    public static void main(String[] args) {
        DateTimeFormatter original = DateTimeFormatter
                .ofPattern("uuuuMMddHHmmss")
                .withResolverStyle(ResolverStyle.STRICT);
        DateTimeFormatter novo = DateTimeFormatter
                .ofPattern("uuuu-MM-dd HH:mm:ss")
                .withResolverStyle(ResolverStyle.STRICT);

        LocalDateTime dataHora = LocalDateTime.parse("20161109103000", original);
        String formatado = dataHora.format(novo);
        System.out.println(formatado);
    }
}

See here working on ideone.

And see this question and its answer to learn more about the API java.time.

And it is important to remember that objects of the type DateTimeFormatter only need to be created once and can be reused at will. You can put them in static variables. This is something that does not occur with the SimpleDateFormat.

Browser other questions tagged

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