I currently use this code:
// Pega a hora
Date hora = new Date();
hora.getTime();
It returns me this:
Thu Aug 28 21:55:42 BRT 2014
I'd like a way to get only hour, minute, and second. How to do this?
I currently use this code:
// Pega a hora
Date hora = new Date();
hora.getTime();
It returns me this:
Thu Aug 28 21:55:42 BRT 2014
I'd like a way to get only hour, minute, and second. How to do this?
A very simple way is to use SimpleDateFormat
:
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date hora = Calendar.getInstance().getTime(); // Ou qualquer outra forma que tem
String dataFormatada = sdf.format(hora);
As you are using the Android tag, I highly recommend the Android platform documentation for SimpleDateFormat
which has some details that the Java platform may not have.
If you need to work with the device locale for date, take a look at the documentation that will help you.
As warned, when using SimpleDateFormat on Android, lint
recommends using Locale
.
One of the solutions would be:
// Isso era buscar o locale do dispositivo
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
Other ways are:
SimpleDateFormat.getTimeInstance()
// ou
SimpleDateFormat.getTimeInstace(int style);
// ou
SimpleDateFormat.getTimeInstance(int style, Locale locale);
The style
attribute can take one of the values:
DateFormat.FULL
DateFormat.LONG
DateFormat.MEDIUM
DateFormat.SHORT
DateFormat.DEFAULT
Just as an example of formatting, the result for each style is:
DateFormat.FULL -> 10:46:28 PM Brasilia Standard Time
DateFormat.LONG -> 10:46:28 PM GMT-03:00
DateFormat.MEDIUM -> 10:46:28 PM
DateFormat.SHORT -> 10:46 PM
DateFormat.DEFAULT -> 10:46:28 PM
Try:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Brazil/East"));
int ano = calendar.get(Calendar.YEAR);
int mes = calendar.get(Calendar.MONTH); // O mês vai de 0 a 11.
int semana = calendar.get(Calendar.WEEK_OF_MONTH);
int dia = calendar.get(Calendar.DAY_OF_MONTH);
int hora = calendar.get(Calendar.HOUR_OF_DAY);
int minuto = calendar.get(Calendar.MINUTE);
int segundo = calendar.get(Calendar.SECOND);