Change the format of a date(time) in a String

Asked

Viewed 318 times

3

I have two strings that receive hours, in this case, Arrivaltime and Departuretime. The format that comes is HH:MM:SS. I would like to format this string to HH:MM how can I do this?

Insert this text in Togglebuttons (setTextOn and setTextOff).

3 answers

6


You need to use the Simpledateformat, thus:

public String getHourFormat(String hour){

    SimpleDateFormat dateFormatter = new SimpleDateFormat("HH:mm:ss");
    Date date;
    String displayValue = null;

    try {
        date = dateFormatter.parse(hour);
        SimpleDateFormat timeFormatter = new SimpleDateFormat("HH:mm");
        displayValue = timeFormatter.format(date);

    } catch (ParseException e) {
        e.printStackTrace();
    }

    return displayValue;

}

Just call the method by passing the value, example:

texview.setText(getHourFormat("18:00:00"));

The result in textview will be 18:00

  • The answers answered, but this was exactly what I needed. Thank you very much!

5

Generic method that converts any format into any other:

public static 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;
}

In your case use like this:

setTextOn.setText(trocaFormatoData(jsonValue, "HH:mm:ss", "HH:mm"));

1

One way would be to convert toString to and break this string using split

String string = "11:12:13"; 
String[] partes = string.split(":"); 
partes[0]; // 11
partes[1]; // 12
partes[2]; // 13
  • Use native Java date/time formatters (ex most common: SimpleDateFormat) would give a more robust result.

Browser other questions tagged

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