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


当前回答

实际上,使用time . getcurrenttimezone()在设备上设置当前时区更安全,否则您将获得UTC的当前时间。

Time today = new Time(Time.getCurrentTimezone());
today.setToNow();

然后,你可以得到你想要的所有日期字段,例如:

textViewDay.setText(today.monthDay + "");             // Day of the month (1-31)
textViewMonth.setText(today.month + "");              // Month (0-11)
textViewYear.setText(today.year + "");                // Year 
textViewTime.setText(today.format("%k:%M:%S"));  // Current time

详情请参阅android.text.format.Time类。

更新

正如许多人指出的那样,谷歌说这个类有一些问题,不应该再使用了:

This class has a number of issues and it is recommended that GregorianCalendar is used instead. Known issues: For historical reasons when performing time calculations all arithmetic currently takes place using 32-bit integers. This limits the reliable time range representable from 1902 until 2037.See the wikipedia article on the Year 2038 problem for details. Do not rely on this behavior; it may change in the future. Calling switchTimezone(String) on a date that cannot exist, such as a wall time that was skipped due to a DST transition, will result in a date in 1969 (i.e. -1, or 1 second before 1st Jan 1970 UTC). Much of the formatting / parsing assumes ASCII text and is therefore not suitable for use with non-ASCII scripts.

其他回答

要获取当前时间,您可以使用System.currentTimeMillis(),这是Java中的标准。然后您可以使用它来创建日期

Date currentDate = new Date(System.currentTimeMillis());

正如其他人提到的创造一个时间

Time currentTime = new Time();
currentTime.setToNow();

你可以简单地使用下面的代码:

 DateFormat df = new SimpleDateFormat("HH:mm"); // Format time
 String time = df.format(Calendar.getInstance().getTime());

 DateFormat df1 = new SimpleDateFormat("yyyy/MM/dd"); // Format date
 String date = df1.format(Calendar.getInstance().getTime());

你也可以使用android.os.SystemClock。 例如,SystemClock.elapsedRealtime()将在手机处于睡眠状态时为您提供更准确的时间读数。

Time now = new Time();
now.setToNow();

试试这个对我也有用。

你可以通过以下方法获取日期:

Time t = new Time(Time.getCurrentTimezone());
t.setToNow();
String date = t.format("%Y/%m/%d");

这将给你一个漂亮的表单结果,如这个例子:"2014/02/09"。