Display the current time and date in an Android application
Asked Answered
A

23

209

How do I display the current date and time in an Android application?

Ariannearianrhod answered 16/2, 2010 at 7:2 Comment(0)
E
310

Okay, not that hard as there are several methods to do this. I assume you want to put the current date & time into a TextView.

String currentDateTimeString = java.text.DateFormat.getDateTimeInstance().format(new Date());

// textView is the TextView view that should display it
textView.setText(currentDateTimeString);

There is more to read in the documentation that can easily be found here . There you'll find more information on how to change the format used for conversion.

Effloresce answered 16/2, 2010 at 7:44 Comment(5)
Please - be more explicit! What's the error? Did you import the wrong DateFormat class? It's java.text.DateFormat and NOT android.text.format.DateFormat! And it's java.util.Date and NOT java.sql.Date! Just a little hint on asking questions: try to be precise, e.g.: declare what you mean by "display" in your question. And when you type in my lines - both Date and DateFormat must, of course, be imported - if there's a choice of 2 for each, the least you could try is any combination: it's just 4!Effloresce
sorry sir, i got date not time.similarly can we get time ?Ariannearianrhod
Have a look at developer.android.com/reference/java/text/SimpleDateFormat.html - there you can see how to define exactly what you want to be in your output string. E.g. for time use "HH:mm:ss"! Completely: currentTimeString = new SimpleDateFormat("HH:mm:ss").format(new Date());Effloresce
There's also DateFormat.getTimeInstance() and DateFormat.getDateTimeInstance().Pancreas
How efficient is this? Let's say you need to get time from a constantly firing method. Is there anything more efficient than creating a new Date object each time?Enos
A
126
public class XYZ extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);

        Calendar c = Calendar.getInstance();
        System.out.println("Current time => "+c.getTime());

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedDate = df.format(c.getTime());
        // formattedDate have current date/time
        Toast.makeText(this, formattedDate, Toast.LENGTH_SHORT).show();


      // Now we display formattedDate value in TextView
        TextView txtView = new TextView(this);
        txtView.setText("Current Date and Time : "+formattedDate);
        txtView.setGravity(Gravity.CENTER);
        txtView.setTextSize(20);
        setContentView(txtView);
    }

}

enter image description here

Astrid answered 4/11, 2011 at 10:58 Comment(2)
android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N (24).Enzootic
How to declare SimpleDateFormat because I have got can not find symbol classPlage
E
52
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);
    Thread myThread = null;

    Runnable runnable = new CountDownRunner();
    myThread= new Thread(runnable);   
    myThread.start();

}

public void doWork() {
    runOnUiThread(new Runnable() {
        public void run() {
            try{
                TextView txtCurrentTime= (TextView)findViewById(R.id.lbltime);
                    Date dt = new Date();
                    int hours = dt.getHours();
                    int minutes = dt.getMinutes();
                    int seconds = dt.getSeconds();
                    String curTime = hours + ":" + minutes + ":" + seconds;
                    txtCurrentTime.setText(curTime);
            }catch (Exception e) {}
        }
    });
}


class CountDownRunner implements Runnable{
    // @Override
    public void run() {
            while(!Thread.currentThread().isInterrupted()){
                try {
                doWork();
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                }catch(Exception e){
                }
            }
    }
}
Enclave answered 21/7, 2010 at 10:39 Comment(2)
@Harshit this function comes with the Android SDK as long as your class extends ActivityAlright
I know this is old question, but if somebody will find it in google like me, he should know that the methods Date.getX are deprecated.Anglian
N
42

The obvious choices for displaying the time are the AnalogClock View and the DigitalClock View.

For example, the following layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" 
    android:orientation="vertical">

    <AnalogClock
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"/>

    <DigitalClock 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:gravity="center" 
        android:textSize="20sp"/>
</LinearLayout>

Looks like this:

screenshot

Nevins answered 16/2, 2010 at 9:1 Comment(4)
dear sir, i want to display current time using setText.Ariannearianrhod
I feel like a stupid shit after reading this obvious answer! I implemented my own runnable, putting it to sleep for a given amount of time and so on when the obvious answer was a XML-one-liner! Many thanks (more than a year after your post) :-)Attainture
In 2015 it's deprecated and It is recommended you use TextClock instead. :)Equation
AnalogClock is deprecated in API level 23. and AnalogClock and DigitalClock only show current time, but not current date.Lepidolite
C
36

In case you want a single line of code:

String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());

The result is "2016-09-25 16:50:34"

Checkroom answered 25/9, 2016 at 13:20 Comment(0)
L
22

My own working solution:

Calendar c = Calendar.getInstance();

String sDate = c.get(Calendar.YEAR) + "-" 
+ c.get(Calendar.MONTH)
+ "-" + c.get(Calendar.DAY_OF_MONTH) 
+ " at " + c.get(Calendar.HOUR_OF_DAY) 
+ ":" + c.get(Calendar.MINUTE);

Hope this helps!

Lovegrass answered 8/6, 2011 at 11:43 Comment(3)
I wonder why c.get(Calendar.MONTH) returns 5 when it is supposedly 6? My device has correct time settings.Reeder
Oh yeah, but why do they have to do that when the other variables were accurate. :)Reeder
Calendar c = Calendar.getInstance(); int month = c.get(Calendar.MONTH) + 1; String sDate = month + "-" + c.get(Calendar.DAY_OF_MONTH) + "-" + c.get(Calendar.YEAR) + "-" + c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE); that works fineAtlante
C
20

If you want to get the date and time in a specific pattern you can use

Date d = new Date();
CharSequence s = DateFormat.format("yyyy-MM-dd hh:mm:ss", d.getTime());
Custombuilt answered 29/1, 2012 at 6:15 Comment(0)
C
14

From How to get full date with correct format?:

Please, use

android.text.format.DateFormat.getDateFormat(Context context)
android.text.format.DateFormat.getTimeFormat(Context context)

to get valid time and date formats in sense of current user settings (12/24 time format, for example).

import android.text.format.DateFormat;

private void some() {
    final Calendar t = Calendar.getInstance();
    textView.setText(DateFormat.getTimeFormat(this/*Context*/).format(t.getTime()));
}
Cipango answered 27/10, 2011 at 21:6 Comment(0)
T
11

Here is the code which worked for me. Please try this. It is a simple method which takes time and date from a system call.

public static String getDatetime() {
    Calendar c = Calendar .getInstance();
    System.out.println("Current time => "+c.getTime());
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mms");
    String formattedDate = df.format(c.getTime());
    return formattedDate;
}
Theotheobald answered 12/5, 2014 at 7:30 Comment(0)
C
8

Use:

Calendar c = Calendar.getInstance();

int seconds = c.get(Calendar.SECOND);
int minutes = c.get(Calendar.MINUTE);
int hour = c.get(Calendar.HOUR);
String time = hour + ":" + minutes + ":" + seconds;


int day = c.get(Calendar.DAY_OF_MONTH);
int month = c.get(Calendar.MONTH);
int year = c.get(Calendar.YEAR);
String date = day + "/" + month + "/" + year;

// Assuming that you need date and time in a separate
// textview named txt_date and txt_time.

txt_date.setText(date);
txt_time.setText(time);
Consternation answered 22/7, 2014 at 5:10 Comment(0)
S
7
String formattedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime()); 

Use formattedDate as your String filled with the date.
In my case: mDateButton.setText(formattedDate);

Suppository answered 24/9, 2013 at 11:53 Comment(0)
N
7

Actually, you're best off with the TextClock widget. It handles all of the complexity for you and will respect the user's 12/24hr preferences. http://developer.android.com/reference/android/widget/TextClock.html

Nickles answered 2/5, 2014 at 15:25 Comment(0)
T
7

To display the current date function:

Calendar c = Calendar.getInstance();

SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String date = df.format(c.getTime());
Date.setText(date);

You must want to import

import java.text.SimpleDateFormat; import java.util.Calendar;

You must want to use

TextView Date;
Date = (TextView) findViewById(R.id.Date);
Totaquine answered 15/1, 2017 at 5:55 Comment(0)
I
6
Calendar c = Calendar.getInstance();
int month=c.get(Calendar.MONTH)+1;
String sDate = c.get(Calendar.YEAR) + "-" + month+ "-" + c.get(Calendar.DAY_OF_MONTH) +
"T" + c.get(Calendar.HOUR_OF_DAY)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND);

This will give date time format like 2010-05-24T18:13:00

Inverness answered 14/3, 2012 at 4:59 Comment(0)
A
5

This would give the current date and time:

public String getCurrDate()
{
    String dt;
    Date cal = Calendar.getInstance().getTime();
    dt = cal.toLocaleString();
    return dt;
}
Abney answered 27/7, 2011 at 11:4 Comment(0)
L
5

Simply copy this code and hope this works fine for you.

Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
String strDate = sdf.format(c.getTime());
Lark answered 20/7, 2015 at 8:10 Comment(0)
H
3

Try the below code:

SimpleDateFormat dateFormat = new SimpleDateFormat(
                                    "yyyy/MM/dd HH:mm:ss");

Calendar cal = Calendar.getInstance();
System.out.println("time => " + dateFormat.format(cal.getTime()));

String time_str = dateFormat.format(cal.getTime());

String[] s = time_str.split(" ");

for (int i = 0; i < s.length; i++) {
     System.out.println("date  => " + s[i]);
}

int year_sys = Integer.parseInt(s[0].split("/")[0]);
int month_sys = Integer.parseInt(s[0].split("/")[1]);
int day_sys = Integer.parseInt(s[0].split("/")[2]);

int hour_sys = Integer.parseInt(s[1].split(":")[0]);
int min_sys = Integer.parseInt(s[1].split(":")[1]);

System.out.println("year_sys  => " + year_sys);
System.out.println("month_sys  => " + month_sys);
System.out.println("day_sys  => " + day_sys);

System.out.println("hour_sys  => " + hour_sys);
System.out.println("min_sys  => " + min_sys);
Holmquist answered 24/4, 2013 at 9:29 Comment(0)
E
3
String currentDateandTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
Toast.makeText(getApplicationContext(), currentDateandTime, Toast.LENGTH_SHORT).show();
Extrasystole answered 30/1, 2017 at 9:54 Comment(0)
H
3

You Can try this way

Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("HH:mm:ss");
String strDate = "Current Time : " + mdformat.format(calendar.getTime());
Handoff answered 9/6, 2018 at 8:53 Comment(0)
W
2

If you wish to work with date/time in android I recommend you to use ThreeTenABP which is a version of java.time.* package (available starting from API 26 on android) shipped with Java 8 available as a replacement for java.util.Date and java.util.Calendar.

LocalDate localDate = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
String date = localDate.format(formatter);
textView.setText(date);
Wainwright answered 16/12, 2019 at 13:54 Comment(2)
Just to set it straight, I am sure you meant the correct thing: java.time is built in from Android API level 26. ThreeTenABP is what you use to get virtually the same functionality on lower API levels. So the code can work on both low and high levels.Readiness
And since the question was about displaying date and time, for that purpose one may use for example a ZonedDateTime instead of LocalDate and DateTimeFormatter.ofLocalizedDateTime instead of ofLocalizedDate. Otherwise the code will be the same.Readiness
H
1

For Show Current Date and Time on Textview

    /// For Show Date
    String currentDateString = DateFormat.getDateInstance().format(new Date());
    // textView is the TextView view that should display it
    textViewdate.setText(currentDateString);
    /// For Show Time
    String currentTimeString = DateFormat.getTimeInstance().format(new Date());
    // textView is the TextView view that should display it
    textViewtime.setText(currentTimeString);

Check full Code Android – Display the current date and time in an Android Studio Example with source code

Hatband answered 8/3, 2018 at 6:17 Comment(0)
U
0

To get current Time/Date just use following code snippet:

To use Time:

SimpleDateFormat simpleDateFormatTime = new SimpleDateFormat("HH:mm", Locale.getDefault());
String strTime = simpleDateFormatTime.format(now.getTime());

To use Date:

SimpleDateFormat simpleDateFormatDate = new SimpleDateFormat("E, MMM dd, yyyy", Locale.getDefault());    
String strDate = simpleDateFormatDate.format(now.getTime());

and you are good to go.

Unexpressive answered 16/10, 2017 at 7:51 Comment(0)
S
0
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
Date date = Calendar.getInstance().getTime();
String sDate = format.format(date);//31-12-9999
int mYear = c.get(Calendar.YEAR);//9999
int mMonth = c.get(Calendar.MONTH);
mMonth = mMonth + 1;//12
int hrs = c.get(Calendar.HOUR_OF_DAY);//24
int min = c.get(Calendar.MINUTE);//59
String AMPM;
if (c.get(Calendar.AM_PM) == 0) {
    AMPM = "AM";
} else {
    AMPM = "PM";
}
Suckerfish answered 12/3, 2018 at 6:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.