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

3

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

I enter this text in ToggleButtons (setTextOn and setTextOff).

    
asked by anonymous 20.10.2016 / 18:54

3 answers

6

You need to use SimpleDateFormat , like this:

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, eg:

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

The result in the textview will be 18:00

    
20.10.2016 / 19:06
5

Generic method that converts any format to 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 this:

setTextOn.setText(trocaFormatoData(jsonValue, "HH:mm:ss", "HH:mm"));
    
20.10.2016 / 19:15
1

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

String string = "11:12:13"; 
String[] partes = string.split(":"); 
partes[0]; // 11
partes[1]; // 12
partes[2]; // 13
    
20.10.2016 / 19:08