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


当前回答

如果你想以特定的模式获取日期和时间,你可以使用以下命令:

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());
String currentDateandTime = sdf.format(new Date());

Or,

日期:

String currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());

时间:

String currentTime = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new Date());

其他回答

final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);

textView.setText("" + mDay + "-" + mMonth + "-" + mYear);

如果需要当前日期:

Calendar cc = Calendar.getInstance();
int year = cc.get(Calendar.YEAR);
int month = cc.get(Calendar.MONTH);
int mDay = cc.get(Calendar.DAY_OF_MONTH);
System.out.println("Date", year + ":" + month + ":" + mDay);

如果需要当前时间:

 int mHour = cc.get(Calendar.HOUR_OF_DAY);
 int mMinute = cc.get(Calendar.MINUTE);
 System.out.println("time_format" + String.format("%02d:%02d", mHour , mMinute));

对于当前日期和时间,使用:

String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());

输出:

Feb 27, 2012 5:41:23 PM

如果你想以特定的模式获取日期和时间,你可以使用以下命令:

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());
String currentDateandTime = sdf.format(new Date());

Or,

日期:

String currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());

时间:

String currentTime = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new Date());

试试这个

String mytime = (DateFormat.format("dd-MM-yyyy hh:mm:ss", new java.util.Date()).toString());