i use this code to show current time in TimePicker, but i don't know really,why it doesn't show correctly!? for example now time (system time) is 2:56 PM, but it shows 2:56 AM!. how can i solve it? thanks.
private long timer1 = 0;
...
switch (view.getId()) {
case R.id.add1: {
if (timer1 == 0) {
timer1 = getCurrentTime();
}
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timer1);
TimePicker timePicker = (TimePicker) findViewById(R.id.tp_1);
timePicker.setCurrentHour(calendar.get(Calendar.HOUR));
timePicker.setCurrentMinute(calendar.get(Calendar.MINUTE));
break;
. ..
}
private long getCurrentTime() {
Calendar calendar = GregorianCalendar.getInstance();
return calendar.getTimeInMillis();
}
and also i have the same problem when i want to convert this time into String form with this method below:
private String convertTimeToString(long time) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(time);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
//int hour = get;
int minute = calendar.get(Calendar.MINUTE);
String timeSet;
if (hour > 12) {
hour -= 12;
timeSet = "PM";
} else if (hour == 0) {
hour += 12;
timeSet = "AM";
} else if (hour == 12) {
timeSet = "PM";
} else {
timeSet = "AM";
}
String minutes;
if (minute < 10) {
minutes = "0" + minute;
} else {
minutes = String.valueOf(minute);
}
// Append in a StringBuilder
return String.format("%s:%s %s", hour, minutes, timeSet);
}
please help me!
Updated
1) wrong hour problem: Try to edit code like this:
...
timePicker.setCurrentHour(calendar.get(Calendar.HOUR_OF_DAY));
...
2) string representation problem: general approach to convert date/time to string is following:
String format = "hh:mm"; // or any other format - see note below
SimpleDateFormat formatter = new SimpleDateFormat(format);
formatter.format(yourDate);
or when you use long
timestamp last line will be:
formatter.format(new Date(yourLongTimestamp));
Useful links:
Different date/time format symbols you may look here.
Test different format patterns you may here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With