Android获取当前date并在TextView中显示

我不知道下面的代码有什么问题 –

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView tv = (TextView) findViewById(R.id.textView1); String dt; Date cal = (Date) Calendar.getInstance().getTime(); dt = cal.toLocaleString(); tv.setText(dt.toString()); } 

Solutions Collecting From Web of "Android获取当前date并在TextView中显示"

我build议:

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

以下面的示例格式显示

Mon Jan 5, 2009 4:55 PM

你可以使用任何你想要的格式 – 选项可以在Oraclefind

使用这个代码:

 tvDisplayDate = (TextView) findViewById(R.id.tvDate); final Calendar c = Calendar.getInstance(); yy = c.get(Calendar.YEAR); mm = c.get(Calendar.MONTH); dd = c.get(Calendar.DAY_OF_MONTH); // set current date into textview tvDisplayDate.setText(new StringBuilder() // Month is 0 based, just add 1 .append(yy).append(" ").append("-").append(mm + 1).append("-") .append(dd)); 

下面的解决scheme可能有帮

 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(" ")); } 
  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); 
 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss"); String currentDateandTime = sdf.format(new Date()); tv.setText(currentDateandTime); 

这是我如何做到这一点

注意*:

 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); 

如果你想生成一个吐司当前时间点击button,然后使用此代码。

 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(); } }); 

考虑使用TextClock,因为它会为您处理更新。 有关更多信息,请参阅文档文档 。 如果您的目标只是显示当前时间和date,则AnalogClock和DigitalClock也可能非常有用

  <TextClock android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="30sp" android:format24Hour="MMM,yyyy\n\thh:mm"/> 
 Calendar c = Calendar.getInstance(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String formattedDate = df.format(c.getTime()); System.out.println("Currrent Date Time : "+formattedDate);