Get current time and date on Android

2018-12-31 04:00发布

How can I get the current time and date in an Android app?

30条回答
十年一品温如言
2楼-- · 2018-12-31 04:30

Try this code it display current date and time

 Date date = new Date(System.currentTimeMillis());
 SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm aa",
                         Locale.ENGLISH);
 String var = dateFormat.format(date));
查看更多
若你有天会懂
3楼-- · 2018-12-31 04:31

You can (but no longer should - see below!) use android.text.format.Time:

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

From the reference linked above:

The Time class is a faster replacement for the java.util.Calendar and java.util.GregorianCalendar classes. An instance of the Time class represents a moment in time, specified with second precision.


NOTE 1: It's been several years since I wrote this answer, and it is about an old, Android-specific and now deprecated class. Google now says that "[t]his class has a number of issues and it is recommended that GregorianCalendar is used instead".


NOTE 2: Even though the Time class has a toMillis(ignoreDaylightSavings) method, this is merely a convenience to pass to methods that expect time in milliseconds. The time value is only precise to one second; the milliseconds portion is always 000. If in a loop you do

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 ...

The resulting sequence will repeat the same value, such as 1410543204000, until the next second has started, at which time 1410543205000 will begin to repeat.

查看更多
像晚风撩人
4楼-- · 2018-12-31 04:31

For the current date and time, use:

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

Which outputs:

Feb 27, 2012 5:41:23 PM
查看更多
柔情千种
5楼-- · 2018-12-31 04:32

There are several options as Android is mainly Java, but if you wish to write it in a textView, the following code would do the trick:

String currentDateTimeString = DateFormat.getDateInstance().format(new Date());

// textView is the TextView view that should display it
textView.setText(currentDateTimeString);
查看更多
人间绝色
6楼-- · 2018-12-31 04:33

To ge the current time you can use System.currentTimeMillis() which is standard in Java. Then you can use it to create a date

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

And as mentioned by others to create a time

Time currentTime = new Time();
currentTime.setToNow();
查看更多
浅入江南
7楼-- · 2018-12-31 04:33
Date todayDate = new Date();
todayDate.getDay();
todayDate.getHours();
todayDate.getMinutes();
todayDate.getMonth();
todayDate.getTime();
查看更多
登录 后发表回答