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


当前回答

您应该根据新的API使用calendar类。Date类现在已弃用。

Calendar cal = Calendar.getInstance();

String date = "" + cal.get(Calendar.DATE) + "-" + (cal.get(Calendar.MONTH)+1) + "-" + cal.get(Calendar.YEAR);

String time = "" + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE);

其他回答

Android中的当前时间和日期格式

Calendar c = Calendar.getInstance();
System.out.println("Current dateTime => " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss a");
String formattedDate = df.format(c.getTime());
System.out.println("Format dateTime => " + formattedDate);

输出

I/System.out: Current dateTime => Wed Feb 26 02:58:17 GMT+05:30 2020
I/System.out: Format dateTime => 26-02-2020 02:58:17 AM
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);

你可以(但不再应该-见下文!)使用android.text.format.Time:

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

从上面的参考链接:

Time类是一个更快的替代品 为java.util.Calendar和 java.util.GregorianCalendar类。 Time类的实例 表示指定的时间点 精准度第二。


注1: 我写这个答案已经有好几年了, 它是关于一个旧的,android专用的,现在已被弃用的类。 谷歌现在这样说 “他的类有一些问题,建议使用公历代替”。


注2:尽管Time类有一个toMillis(ignoreDaylightSavings)方法,但这只是为了方便传递给以毫秒为单位的方法。时间值仅精确到一秒;毫秒部分总是000。如果在循环中,你会这样做

Time time = new Time();   time.setToNow();
Log.d("TIME TEST", Long.toString(time.toMillis(false)));
... do something that takes more than one millisecond, but less than one second ...

结果序列将重复相同的值,例如1410543204000,直到下一秒开始,此时1410543205000将开始重复。

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

试试这个对我也有用。

好吧,我有一些问题的答案的API,所以我融合了这段代码:

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

Date date = new Date(System.currentTimeMillis());
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm aa", Locale.ENGLISH);
String var = dateFormat.format(date);
String horafecha = var+ " - " + date1;

tvTime.setText(horafecha);

输出:

03:25 PM - 2017/10/03