Problem with android conversion

Asked

Viewed 388 times

3

I have a date that’s being returned from a Webservice like this:

Sep 22, 2014 12:00:00 AM

I would like to convert it to the following format?

22/09/2014 

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

NOTE: The date comes from Webservice in format String.

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 reply soen

This function can be made more generic in order 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;
}
  • Thank you very much!

  • http://answall.com/questions/38587/trocar-data-dando-erro

Browser other questions tagged

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