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).
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).
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
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"));
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