如何在两个单独的TextView中打印系统日期和系统时间?
答案 0 :(得分:1)
使用日历并获取时间和日期
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
if (c.get(Calendar.AM_PM) == Calendar.AM)
am_pm = "AM";
else if (c.get(Calendar.AM_PM) == Calendar.PM)
am_pm = "PM";
并使用此
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = df.format(c.getTime());
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);
答案 1 :(得分:1)
实际上,使用Time.getCurrentTimezone()设置设备上的当前时区更安全,否则您将获得UTC的当前时间。
Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
然后,您可以获得所需的所有日期字段,例如:
textViewDay.setText(today.monthDay); // Day of the month (0-31)
textViewMonth.setText(today.month); // Month (0-11)
textViewYear.setText(today.year); // Year
textViewTime.setText(today.format("%k:%M:%S")); // Current time
有关所有详细信息,请参阅http://developer.android.com/reference/android/text/format/Time.html课程。
答案 2 :(得分:0)
TextView tvDate = (TextView)findViewById(R.id.dateText);
TextView tvTime = (TextView)findViewById(R.id.timeText);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss a");
Calendar c = Calendar.getInstance();
tvDate.setText(dateFormat.format(c.getTime()));
tvTime.setText(timeFormat.format(c.getTime()));