如何在Android应用程序中显示当前日期和时间?


当前回答

SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
Date date = Calendar.getInstance().getTime();
String sDate = format.format(date);//31-12-9999
int mYear = c.get(Calendar.YEAR);//9999
int mMonth = c.get(Calendar.MONTH);
mMonth = mMonth + 1;//12
int hrs = c.get(Calendar.HOUR_OF_DAY);//24
int min = c.get(Calendar.MINUTE);//59
String AMPM;
if (c.get(Calendar.AM_PM) == 0) {
    AMPM = "AM";
} else {
    AMPM = "PM";
}

其他回答

如果你想要一行代码:

String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());

结果是“2016-09-25 16:50:34”

你可以试试这种方法

Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("HH:mm:ss");
String strDate = "Current Time : " + mdformat.format(calendar.getTime());

要获得当前的时间/日期,只需使用以下代码片段:

使用时间:

SimpleDateFormat simpleDateFormatTime = new SimpleDateFormat("HH:mm", Locale.getDefault());
String strTime = simpleDateFormatTime.format(now.getTime());

使用日期:

SimpleDateFormat simpleDateFormatDate = new SimpleDateFormat("E, MMM dd, yyyy", Locale.getDefault());    
String strDate = simpleDateFormatDate.format(now.getTime());

这样就可以开始了。

这将给出当前的日期和时间:

public String getCurrDate()
{
    String dt;
    Date cal = Calendar.getInstance().getTime();
    dt = cal.toLocaleString();
    return dt;
}

我自己的工作解决方案:

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

希望这能有所帮助!