Ajinkya More
Ajinkya More

Reputation: 425

Showing current time in Android and updating it?

I want to display current time and keep it updating, in this format example: 09:41 Hour:Minute. Is it possible to do in TextView? I tried some ways but I'm not getting what I actually want.

Upvotes: 11

Views: 25523

Answers (6)

Duong.Nguyen
Duong.Nguyen

Reputation: 413

For someone who needing a custom date and time directly by using TextClock

  • Format for time: android:format12Hour="hh:mm:ss a"
  • Format for date: android:format24Hour="MMM dd, yyyy"
<androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/layoutContent"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/bg_screenlock"
        app:layout_constraintStart_toStartOf="parent">

        <TextClock
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="60dp"
            android:gravity="center"
            android:textColor="@color/_white"
            android:textSize="70sp"
            android:format12Hour="hh:mm:ss a"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextClock
            android:id="@+id/textDateTime"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:textColor="@color/_white"
            android:textSize="28sp"
            android:format24Hour="MMM dd, yyyy"
            app:layout_constraintTop_toBottomOf="@+id/textView" />
 </androidx.constraintlayout.widget.ConstraintLayout>


[![date_time_update_directly][1]][1]


  [1]: https://i.sstatic.net/JZWUj.png

Upvotes: 3

Bojan Kseneman
Bojan Kseneman

Reputation: 15668

Something like this should do the trick

final Handler someHandler = new Handler(getMainLooper());   
        someHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                tvClock.setText(new SimpleDateFormat("HH:mm", Locale.US).format(new Date()));
                someHandler.postDelayed(this, 1000);
            }
        }, 10);

You should keep a reference to the handler and the runnable to cancel this when the Activity goes to pause and resume when it resumes. Make sure you remove all callbacks to handler and set it to null in onDestroy

Upvotes: 15

rodit
rodit

Reputation: 1766

Why not use Java's Timer and TimerTask? They're very easy, reliable and simple to understand.

Here is an example:

public class ClockCounter extends TimerTask{

    private long time = System.currentTimeMillis();

    @Override
    public void run(){
        time += 1000; //add 1 second to the time
        //convert ms time to viewable time and set MainActivity.text (textview) text to this.
    }

    public long getTime(){ return time; }
}

public class MainActiviy extends Activity{

    public static TextView text;
    private Timer timer;

    @Override
    public void onCreate(){
        //default code
        //set text view according to id
        timer = new Timer();
        timer.schedule(new ClockCounter(), 0, 1000); //schedule clock counter to repeat every 1 seconds (1000 ms)
    }
}

I know there are some notes of what to do in there but any android developer with reasonable experience in Java should be able to figure out how to do those things.

I hope this helped!

EDIT To format the date to a viewable string, you can use the following code (also using only Java's shipped APIs)

Date date = new Date();
DateFormat formatter = new SimpleDateFormat("HH:mm"); //Hourse:Minutes
String dateFormatted = formatter.format(date); //string representation

Upvotes: 2

Pallav
Pallav

Reputation: 165

For getting time and date you can use Calender class

Calendar cal = Calendar.getInstance();
String time = ""+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE);

Upvotes: 1

Charaf Eddine Mechalikh
Charaf Eddine Mechalikh

Reputation: 1248

  boolean run=true; //set it to false if you want to stop the timer
  Handler mHandler = new Handler();


 public void timer() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (run) {
                    try {
                        Thread.sleep(20000);
                        mHandler.post(new Runnable() {

                            @Override
                            public void run() {
                                Calendar c = Calendar.getInstance();
                                int min = c.get(Calendar.MINUTE);
                                int hour=c.get(Calendar.HOUR);
                                TextView.setText(String.valueOf(hour)+":"+String.valueOf(min));
                            }
                        });
                    } catch (Exception e) {
                    }
                }
            }
        }).start();}

in the onCreate call it like this

  timer();

Upvotes: 3

dabluck
dabluck

Reputation: 1181

Android has a view for this already.

http://developer.android.com/reference/android/widget/TextClock.html

You can use it directly in XML like so

<TextClock
    android:id="@+id/textClock"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
     />

It is min api 17, so you if need to go lower than that just look into

http://developer.android.com/reference/android/widget/DigitalClock.html

Worst case scenario you can subclass textview and steal the code from the textclock source. it should be fairly straightforward

Upvotes: 22

Related Questions