Format date in java

4

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

I've tried using SimpleDateFormat , DateTimeFormatter and could not format the date.

    
asked by anonymous 22.08.2017 / 15:31

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 variable dataFormatada :

  

2016-11-09 10:30:00

This will create an object type util.Date of the string and then convert it to the desired format in string, again.

See the result in the ideone: link

    
22.08.2017 / 15:34
1

Using the new dava.time API, with 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 your answer to learn more about the java.time API.

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

    
22.08.2017 / 16:13