Problem with android conversion

3

I have a date that is being returned from a WebService like this:

Sep 22, 2014 12:00:00 AM

Would you like to convert it to the following format?

22/09/2014 

I tried some methods using Date of Android and I did not succeed.

NOTE: The date comes from the WebService in String format.

    
asked by anonymous 02.10.2014 / 15:13

1 answer

5

Use the class SimpleDateFormat

public String trocaFormatoData(String data) {

    String formatoDeEntrada = "MMM dd, yyyy h:mm:ss AM";
    String formatoDeSaida = "dd/MM/yyyy";
    SimpleDateFormat dateFormatEntrada = new SimpleDateFormat(formatoDeEntrada);
    SimpleDateFormat dateFormatSaida = new SimpleDateFormat(formatoDeSaida);

    Date dataOriginal = null;
    String dataTrocada = null;

    try {
        //Transforma a String em Date
        dataOriginal = dateFormatEntrada.parse(data);
        //Transforma a Date num String com o formato pretendido
        dataTrocada = dateFormatSaida.format(dataOriginal);
    } catch (ParseException e) {
       //Erro se não foi possível fazer o parse da Data
        e.printStackTrace();
    }
    return dataTrocada;
}

Adapted from a SOen response

This function can be made more generic to change any format in any other. For this the input and output format will be function parameters.

public String trocaFormatoData(String data, String formatoDeEntrada, String formatoDeSaida) {

    SimpleDateFormat dateFormatEntrada = new SimpleDateFormat(formatoDeEntrada);
    SimpleDateFormat dateFormatSaida = new SimpleDateFormat(formatoDeSaida);

    Date dataOriginal = null;
    String dataTrocada = null;

    try {
        //Transforma a String em Date
        dataOriginal = dateFormatEntrada.parse(data);
        //Transforma a Date num String com o formato pretendido
        dataTrocada = dateFormatSaida.format(dataOriginal);
    } catch (ParseException e) {
       //Erro se não foi possível fazer o parse da Data
        e.printStackTrace();
    }
    return dataTrocada;
}
    
02.10.2014 / 18:45