Problem with Calendar.get(Calendar.HOUR)

28,119

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();
Share:
28,119
Jon Rubins
Author by

Jon Rubins

Updated on March 03, 2020

Comments

  • Jon Rubins
    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
    Jon Rubins almost 13 years
    But 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
    Jon Rubins almost 13 years
    Thanks, 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.