0

I have textview i want to display the current date n time but without on click even on button as soon as app is launched it should start ticking date n time

String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
textView.setText(currentDateTimeString);
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
user7026863
  • 61
  • 1
  • 1
  • 4
  • try with this public static String getCurrentDateAndTime() { return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()); } – saeed Nov 21 '16 at 14:49
  • but this will still not start date time ticker when the app launches.. it will reply on some events.. i want to start ticker on textview as soon as app launches – user7026863 Nov 21 '16 at 14:52
  • you can use thread or handler to implement this http://stackoverflow.com/questions/17480936/how-to-display-the-timer-in-android – saeed Nov 21 '16 at 15:01
  • If you need to do something other than just show the time you might want to look into a TimerTask. If it is just to track time there are native widgets that handle that. – zgc7009 Nov 21 '16 at 17:03

3 Answers3

4

use TextClock

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

just put on your layout

<TextClock
    android:id="@+id/textClock"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="30dp"
    android:format12Hour="hh:mm:ss a"
    android:gravity="center_horizontal"
    android:textColor="#d41709"
    android:textSize="44sp"
    android:textStyle="bold" />
yanivtwin
  • 617
  • 8
  • 32
  • Pay attention that TextClock was added in API 17. In case you are using earlier, try DigitalClock https://developer.android.com/reference/android/widget/DigitalClock.html – fbwnd Nov 21 '16 at 15:24
1

Add the code to the onCreate method of your main activity. This code runs when the app is launched.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        <<<<your date and time logic>>>>>

   }

http://factualnote.com/f/j2ci4rrd0unqhfftc74k4ltgh

Dinesh
  • 219
  • 2
  • 14
1

I suggest:

TextView textViewDisplayDate;
long date = System.currentTimeMillis(); 

SimpleDateFormat sdf = new SimpleDateFormat("MMM MM dd, yyyy h:mm a");
String dateString = sdf.format(date);   
textViewDisplayDate.setText(dateString);

which displays in the following example format:- Thu Oct 10, 2019 11:46 AM

You can use whatever format you want - options can be found at Android Documentation

Pramesh Bhalala
  • 273
  • 1
  • 3
  • 9