Problem with Calendar.get(Calendar.HOUR)
Solution 1
Use Calendar.HOUR_OF_DAY for 24h clock
Calendar rightNow = Calendar.getInstance();
mTv.setText("Refreshed! Last updated " +
rightNow.get(Calendar.HOUR_OF_DAY) + ":" +
rightNow.get(Calendar.MINUTE) + ".");
Solution 2
You can update editText
in each minute using a thread like following
Thread t = new Thread(){
public void run() {
Calendar oldTime = Calendar.getInstance();
oldMinute = oldTime .get(Calendar.MINUTE);
while(true) {
Calendar rightNow= Calendar.getInstance();
newMinute = rightNow.get(Calendar.MINUTE);
if(newMinute != oldMinute) {
oldMinute = newMinute;
mTv.setText("Refreshed! Last updated " +
rightNow.get(Calendar.HOUR) + ":" +
rightNow.get(Calendar.MINUTE) + ".");
}
}
}
t.start();
![Jon Rubins](https://i.stack.imgur.com/nEzQI.jpg?s=256&g=1)
Jon Rubins
Updated on March 03, 2020Comments
-
Jon Rubins over 4 years
I am trying to display in a TextView when my application last updated (e.g., "Last updated at 12:13). I am trying to use a Calendar instance and I thought I understood it correctly but I seem to be having trouble. I know to get an instance I use the method Calendar.getInstance(). And then to get the hour and minute I was using Calendar.get(Calendar.HOUR) and Calendar.get(Calendar.MINUTE). My minute field returns correctly but Calendar.HOUR is returning the hour on a 24 hour clock and I want a 12 hour clock. I thought HOUR_OF_DAY was 24 hour clock. Where am I going wrong?
Here is the code I'm using:
Calendar rightNow = Calendar.getInstance(); mTv.setText("Refreshed! Last updated " + rightNow.get(Calendar.HOUR) + ":" + rightNow.get(Calendar.MINUTE) + ".");
mTv is my TextView that I'm updating. Thanks for any help.
Also, it would be ideal if I could say "Last updated 5 minutes ago." instead of "Last updated at 12:13pm". But I'm not sure the best way to have this update each minute without draining resources or the battery...?
-
Jon Rubins almost 13 yearsBut this won't update as each minute passes, right? It will only update right away and then won't change once another minute passes...
-
Jon Rubins almost 13 yearsThanks, but after reading the answer above yours, I've decided I don't need the "Updated x minutes ago" function. This Thread you've suggested seems like it would use a lot of battery with the infinite loop and I'd rather not eat away the battery.