Android – the calendar gives me the wrong time and minutes
I'm trying to get the time of the timestamp, but when I use calendar.hour and calendar.minute, I always get the wrong time. No matter what the timestamp is, it tells me that the hour is 10 and the minute is 12
Now, when I use calendar. Gettime (), it gives me the right time, so I don't understand? I just want to get hours in 12 hour format and minutes
This is how I do it
public static String getRealTime(long time){
Calendar cal = Calendar.getInstance();
Log.d("Calendar",String.valueOf(time));
cal.setTimeInMillis(time);
Date timeS = cal.getTime();
String sTime = timeS.toString(); // gives correct time in 24hr format
int hr = cal.HOUR; // gives me 10 no matter what the timestamp is
int min = cal.MINUTE; // gives me 12 no matter what the timestamp is
String dMin = getDoubleDigit(min);
int ampm = cal.AM_PM;
String m = new String();
if(ampm == 0){
m = "AM";
}else{
m="PM";
}
String rtime = String.valueOf(hr)+":"+dMin+" "+m;
return rtime;
}
So the timestamp is 1316626200000 cal. Gettime() gave me wed SEP 21 13:30:00 EDT 2011, which would be the right time, but cal. Hour gave me 10 hours, which is obviously not what it should be. Why did it do this?
resolvent:
Cal.hour and cal.minute are static final integers used for calendar method calls. You will use this code to get the correct results:
int hr = cal.get(Calendar.HOUR);
int min = cal.get(Calendar.MINUTE);
Please note that I called the hour and minute fields from calendar instead of your object cal. It is not a good practice to call static members from instantiated objects