我不知道下面的代码有什么问题 -
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());
}
答案 0 :(得分:29)
我建议:
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
您可以使用您想要的任何格式 - 可以找到选项at Oracle
答案 1 :(得分:15)
使用此代码:
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));
答案 2 :(得分:5)
以下解决方案可能有所帮助 -
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(" "));
}
答案 3 :(得分:2)
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);
答案 4 :(得分:2)
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String currentDateandTime = sdf.format(new Date());
tv.setText(currentDateandTime);
这就是我这样做的方式
答案 5 :(得分:2)
考虑使用TextClock,因为它会为您处理更新。有关详细信息,请参阅文档Docs。如果您的目标只是显示当前时间和日期,则AnalogClock和DigitalClock也很有用
<TextClock
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:format24Hour="MMM,yyyy\n\thh:mm"/>
答案 6 :(得分:1)
请注意*:
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);
答案 7 :(得分:1)
如果您想要生成一个在按钮上单击显示当前时间的Toast,请使用此代码。
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();
}
});
答案 8 :(得分:0)
package main
import "fmt"
func main() {
fmt.Printf("hello, world\n")
}
答案 9 :(得分:-1)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String currentDateandTime = sdf.format(new Date());
tv.setText(currentDateandTime);