0

I am making an app which is going to be always open into my tablet. I am trying to show the current date and time in real time. For the time, I use below code

<DigitalClock
        android:id="@+id/digitalClock"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:gravity="center"
        android:textColor="#FFFFFF"
        android:textSize="24sp"
        android:textStyle="bold"
        app:layout_constraintTop_toBottomOf="@+id/date"
        tools:layout_editor_absoluteX="0dp" />

And it works perfectly. The app is always open and the time change in real-time (although I am searching now how to add the seconds).

For the date, I used that code

dateTimeDisplay = (TextView)findViewById(R.id.date);
calendar = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE, dd MMMM, yyyy");
date = dateFormat.format(calendar.getInstance().getTime());
dateTimeDisplay.setText(date);

But it shows the current date, not in real-time. It changes only when I open the app.

I can tell because I put seconds in dateFormat to test it and it was static.

SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE, dd MMMM, yyyy , ss");

Have anyone any idea?? Thank you!!

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
ni gi
  • 75
  • 1
  • 10
  • As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use java.time, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Feb 27 '20 at 06:15
  • Please remember to accept the answer if it was helpful (and not to if it wasn’t). Thank you. – Ole V.V. Mar 03 '20 at 21:14

1 Answers1

1

DigitalClock has been deprecated, It is recommended you use TextClock instead.

TextClock will do your job by default. Check below example

<TextClock
        android:id="@+id/textClock1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:format12Hour="hh:mm:ss a"
        android:textColor="#F1511B"
        android:textSize="45dp"
        android:textStyle="bold" />

and for 24-hour format use

android:format24Hour="hh:mm:ss a

Improvement note: Instead of using SimpleDateFormat and helper classes you should use ThreeTenABP as Ole V.V. is indicating in the comment. Here is How to use ThreeTenABP in Android Project

Pankaj Kumar
  • 81,967
  • 29
  • 167
  • 186
  • Thank you, I will make the change.. Do you have maybe any idea for the date? – ni gi Feb 26 '20 at 11:50
  • I just made the change but it shows the same.. Only hour and minutes.. Not seconds.. But at least it is real time.. – ni gi Feb 26 '20 at 12:02
  • 1
    I changed it to android:format24Hour="hh:mm:ss a" and it works! Thank you again! – ni gi Feb 26 '20 at 12:17