Android get current date and show it in TextView

前端 未结 10 2131
清歌不尽
清歌不尽 2021-02-14 09:23

I do not know what is wrong with code below -

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layo         


        
相关标签:
10条回答
  • 2021-02-14 09:42

    if you want to generate a toast which is displaying current time on a button click then use this code.

    bt.setOnClickListener(new OnClickListener() {
    
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Calendar c = Calendar.getInstance();
                hour = c.get(Calendar.HOUR_OF_DAY);
                min = c.get(Calendar.MINUTE);
                int ds = c.get(Calendar.AM_PM);
                if(ds==0)
                AM_PM="pm";
                else
                AM_PM="am";
    
                Toast.makeText(MainActivity.this, ""+hour+":"+min+AM_PM, Toast.LENGTH_SHORT).show();
    
    
            }
        });
    
    0 讨论(0)
  • 2021-02-14 09:44
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
    String currentDateandTime = sdf.format(new Date());
    tv.setText(currentDateandTime);
    

    this is the way how i do it

    0 讨论(0)
  • 2021-02-14 09:45

    Below solution might help -

    final Calendar c = Calendar.getInstance();
    mYear = c.get(Calendar.YEAR);
    mMonth = c.get(Calendar.MONTH);
    mDay = c.get(Calendar.DAY_OF_MONTH);
    
    updateDisplay();
    
    private void updateDisplay() {
        mDateDisplay.setText(
            new StringBuilder()
            // Month is 0 based so add 1
            .append(mMonth + 1).append("-")
            .append(mDay).append("-")
            .append(mYear).append(" "));
    }
    
    0 讨论(0)
  • 2021-02-14 09:45
        TextView tv = (TextView) findViewById(R.id.textView1);
        SimpleDateFormat dfDate_day= new SimpleDateFormat("E, dd/MM/yyyy HH:mm:ss");
        String dt="";
        Calendar c = Calendar.getInstance(); 
        data=dfDate_day.format(c.getTime());
        tv.setText(dt);
    
    0 讨论(0)
  • 2021-02-14 09:46

    I suggest:

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

    which displays in the following example format

    Mon Jan 5, 2009 4:55 PM

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

    0 讨论(0)
  • 2021-02-14 09:51

    note*:

    import java.text.DateFormat;
    import java.util.Date;
    
    // Donot import "import java.sql.Date;"
    
    TextView tv = (TextView) findViewById(R.id.textView1);
    String ct = DateFormat.getDateInstance().format(new Date());
    tv.setText(ct);
    
    0 讨论(0)
提交回复
热议问题