Display the current time and date in an Android ap

2019-01-02 19:40发布

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

标签: android
22条回答
路过你的时光
2楼-- · 2019-01-02 20:06

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"

查看更多
低头抚发
3楼-- · 2019-01-02 20:07
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

查看更多
余生请多指教
4楼-- · 2019-01-02 20:07

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);
查看更多
牵手、夕阳
5楼-- · 2019-01-02 20:08

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

查看更多
素衣白纱
6楼-- · 2019-01-02 20:10
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);

查看更多
残风、尘缘若梦
7楼-- · 2019-01-02 20:11

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!

查看更多
登录 后发表回答