How can i get the time of a TimePicker in this format -> "08:00:00"?
17,511
Solution 1
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
String formatted = format.format(date); // date is a long in milliseconds
Solution 2
TimePicker t = new TimePicker(this);
String formattedTime = "";
int hour = t.getCurrentHour();
String sHour = "00";
if(hour < 10){
sHour = "0"+hour;
} else {
sHour = String.valueOf(hour);
}
int minute = t.getCurrentMinute();
String sMinute = "00";
if(minute < 10){
sMinute = "0"+minute;
} else {
sMinute = String.valueOf(minute);
}
formattedTime = sHour+":"+sMinute+":"+"00"; // Sorry you can't get seconds from a TimePicker
Solution 3
TimePicker
has 2 methods available to get the set time. getCurrentHour
and getCurrentMinute
.
So outputting this as a string shouldn't be too hard.
String s;
Format formatter;
Calendar calendar = Calendar.getInstance();
// tp = TimePicker
calendar.set(Calendar.HOUR_OF_DAY, tp.getCurrentHour());
calendar.set(Calendar.MINUTE, tp.setCurrentMinutes());
calendar.clear(Calendar.SECOND); //reset seconds to zero
formatter = new SimpleDateFormat("HH:mm:ss");
s = formatter.format(calendar.getTime()); // 08:00:00
By the way, lowercase hh
will get you a 12 hour clock.
Solution 4
Just use SimpleDateFormat to format date and time .
Calendar cal=new Calendar();
SimpleDateFormat frmDate=SimpleDateFormat("dd-MM-yyyy");
String s=frmDate.format(cal.getTime());
SimpleDateFormat frmTime=SimpleDateFormat("HH:MM:SS");
String t=frmTime.formate(cal.getTime());
http://developer.android.com/reference/java/text/SimpleDateFormat.html http://developer.android.com/reference/java/text/DateFormat.html
Solution 5
Also check out DateUtils
, very useful.
Author by
NullPointerException
Updated on June 18, 2022Comments
-
NullPointerException almost 2 years
i have a android timepicker, and i need to get his time in java code, and transform it into a string with this appereance: "08:00:00" (hours, mins, secs)
can someone help me to do it in a easy way?
code example will be appreciated