在 Android 上获取当前的时间和日期

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

转载于:https://stackoverflow.com/questions/5369682/get-current-time-and-date-on-android

csdnceshi51
旧行李 43 answers! While many of them were good when they were written, the good answer to use in 2018 is here.
大约 2 年之前 回复

30个回答

You could use:

import java.util.Calendar

Date currentTime = Calendar.getInstance().getTime();

There are plenty of constants in Calendar for everything you need.

Edit:
Check Calendar class documentation

csdnceshi51
旧行李 FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes. Much of the java.time functionality is back-ported to Java 6 & Java 7 in the ThreeTen-Backport project. Further adapted for earlier Android in the ThreeTenABP project. See How to use ThreeTenABP….
接近 3 年之前 回复
csdnceshi62
csdnceshi62 can we use "new Date()" class and format with SimpleDateFormat class?
大约 3 年之前 回复
csdnceshi75
衫裤跑路 As @adamdport says, this doesn't actually answer the question... Calendar.getInstance().getTime() or Calendar.getInstance().getTimeInMillis() will work.
5 年多之前 回复
csdnceshi76
斗士狗 This just gives me the current second, between 0 and 60. Has something changed in the past couple years?
5 年多之前 回复
weixin_41568183
零零乙 +1 this solution has millisecond precision, just what I needed.
接近 7 年之前 回复
csdnceshi55
~Onlooker Yes, it's based on the device time settings/timezone. Quote from the doc: "Calendar's getInstance method returns a calendar whose locale is based on system settings and whose time fields have been initialized with the current date and time" - (above the first samplecode line in the class documentation).
8 年多之前 回复
csdnceshi79
python小菜 But where does this pull the date and time from? the android device setting itself?
8 年多之前 回复
csdnceshi66
必承其重 | 欲带皇冠 Thanks alextsc this what i need
大约 9 年之前 回复
csdnceshi69
YaoRaoLov +1 This was very helpful. Being new it's all these little tidbits we need ... I'm using Calendar to get the Julian date. Much easier than getting milliseconds and figuring out if the value equals today ;)
9 年多之前 回复

Actually, it's safer to set the current timezone set on the device with Time.getCurrentTimezone(), or else you will get the current time in UTC.

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

Then, you can get all the date fields you want, like, for example:

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

See android.text.format.Time class for all the details.

UPDATE

As many people are pointing out, Google says this class has a number of issues and is not supposed to be used anymore:

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.

csdnceshi56
lrony* This class was deprecated in API level 22. We can use GregorianCalendar instead.
接近 5 年之前 回复
csdnceshi62
csdnceshi62 android.text.format like stated above
大约 6 年之前 回复
csdnceshi53
Lotus@ Time should be imported from which package ?
大约 6 年之前 回复

If you want to get the date and time in a specific pattern you can use the following:

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String currentDateandTime = sdf.format(new Date());
weixin_41568196
撒拉嘿哟木头 you can insert sdf.setTimeZone(TimeZone.getDefault()) in the middle
5 年多之前 回复
csdnceshi52
妄徒之命 In short: String currentDateandTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
6 年多之前 回复
weixin_41568174
from.. Yes, but no longer. I didn't realize the overhead involved and had assumed that it was pretty much a POJO.
接近 7 年之前 回复
csdnceshi57
perhaps? T. Mallard : Were you creating new instance of SimpleDateFormat inside onDraw() ??
接近 7 年之前 回复
weixin_41568174
from.. Beware, SimpleDateFormat can be problematic if performance is an issue. In my app I had a custom view that had about 20 HH:MM labels that represented specific times (long integers holding milliseconds), and an equal number of drawable resources. Initial testing showed the interaction was not as fluid as I wanted. When I profiled onDraw() I found that the SimpleTimeFormatter calls were taking 80% of the time. In fact, I'm reading this page as part of a search for a more efficient formatter and to learn more about Calendars, etc.
大约 7 年之前 回复
csdnceshi64
游.程 This will give the time in UTC, should adopt to timezones.
8 年多之前 回复

For those who might rather prefer a customized format, you can use:

DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy, HH:mm");
String date = df.format(Calendar.getInstance().getTime());

Whereas you can have DateFormat patterns such as:

"yyyy.MM.dd G 'at' HH:mm:ss z" ---- 2001.07.04 AD at 12:08:56 PDT
"hh 'o''clock' a, zzzz" ----------- 12 o'clock PM, Pacific Daylight Time
"EEE, d MMM yyyy HH:mm:ss Z"------- Wed, 4 Jul 2001 12:08:56 -0700
"yyyy-MM-dd'T'HH:mm:ss.SSSZ"------- 2001-07-04T12:08:56.235-0700
"yyMMddHHmmssZ"-------------------- 010704120856-0700
"K:mm a, z" ----------------------- 0:08 PM, PDT
"h:mm a" -------------------------- 12:08 PM
"EEE, MMM d, ''yy" ---------------- Wed, Jul 4, '01

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.

csdnceshi65
larry*wei Actually, GregorianCalendar was supplanted years ago in Java and in later Android by the java.time classes, specifically ZonedDateTime. For earlier Android, see the ThreeTen-Backport and ThreeTenABP projects.
2 年多之前 回复
weixin_41568174
from.. > This class was deprecated in API level 22. Use GregorianCalendar instead. See here
5 年多之前 回复
weixin_41568127
?yb? Do not use the Time class. It's going to be removed in the future and has many issues with it.
接近 6 年之前 回复
csdnceshi58
Didn"t forge If you want millisecond accuracy, you are probably doing interval timing, rather than time of day. Android docs recommend SystemClock.uptimeMillis() for interval timing. Since that is what most built-in functions use, there is strong motivation for it to be well-implemented on all devices. See discussion in SystemClock... If you want to correlate that with time of day, in app's onResume, read both this, and Time/setToNow/toMillis. Remember the difference between those.
大约 6 年之前 回复
csdnceshi58
Didn"t forge and Muhammad Babar. No, no, no. Docs say "specified with second precision" Even the simplest test (getting current time in a loop, toMillis, and logging/printing the result) would have showed you that the resulting time has 000 as the millisecond part!
大约 6 年之前 回复

You can also use android.os.SystemClock. For example SystemClock.elapsedRealtime() will give you more accurate time readings when the phone is asleep.

Time time = new Time();
time.setToNow();
System.out.println("time: " + time.hour+":"+time.minute);

This will give you, for example, 12:32.

Remember to import android.text.format.Time;

You can obtain the date by using:

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

This will give you a result in a nice form, as in this example: "2014/02/09".

csdnceshi63
elliott.david The parameterless constructor Time t = new Time(); will use the default timezone. In my experience, default == current.
6 年多之前 回复

You should use Calender class according to new API. Date class is deprecated now.

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);
SimpleDateFormat databaseDateTimeFormate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
SimpleDateFormat databaseDateFormate = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf1 = new SimpleDateFormat("dd.MM.yy");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy.MM.dd G 'at' hh:mm:ss z");
SimpleDateFormat sdf3 = new SimpleDateFormat("EEE, MMM d, ''yy");
SimpleDateFormat sdf4 = new SimpleDateFormat("h:mm a");
SimpleDateFormat sdf5 = new SimpleDateFormat("h:mm");
SimpleDateFormat sdf6 = new SimpleDateFormat("H:mm:ss:SSS");
SimpleDateFormat sdf7 = new SimpleDateFormat("K:mm a,z");
SimpleDateFormat sdf8 = new SimpleDateFormat("yyyy.MMMMM.dd GGG hh:mm aaa");


String currentDateandTime = databaseDateTimeFormate.format(new Date());     //2009-06-30 08:29:36
String currentDateandTime = databaseDateFormate.format(new Date());     //2009-06-30
String currentDateandTime = sdf1.format(new Date());     //30.06.09
String currentDateandTime = sdf2.format(new Date());     //2009.06.30 AD at 08:29:36 PDT
String currentDateandTime = sdf3.format(new Date());     //Tue, Jun 30, '09
String currentDateandTime = sdf4.format(new Date());     //8:29 PM
String currentDateandTime = sdf5.format(new Date());     //8:29
String currentDateandTime = sdf6.format(new Date());     //8:28:36:249
String currentDateandTime = sdf7.format(new Date());     //8:29 AM,PDT
String currentDateandTime = sdf8.format(new Date());     //2009.June.30 AD 08:29 AM

Date format Patterns

G   Era designator (before christ, after christ)
y   Year (e.g. 12 or 2012). Use either yy or yyyy.
M   Month in year. Number of M's determine length of format (e.g. MM, MMM or MMMMM)
d   Day in month. Number of d's determine length of format (e.g. d or dd)
h   Hour of day, 1-12 (AM / PM) (normally hh)
H   Hour of day, 0-23 (normally HH)
m   Minute in hour, 0-59 (normally mm)
s   Second in minute, 0-59 (normally ss)
S   Millisecond in second, 0-999 (normally SSS)
E   Day in week (e.g Monday, Tuesday etc.)
D   Day in year (1-366)
F   Day of week in month (e.g. 1st Thursday of December)
w   Week in year (1-53)
W   Week in month (0-5)
a   AM / PM marker
k   Hour in day (1-24, unlike HH's 0-23)
K   Hour in day, AM / PM (0-11)
z   Time Zone
csdnceshi70
笑故挽风 Although other answers are correct too. I liked this answer as it helps related time related problems too. Thanks @Vighnesh KM
大约 4 年之前 回复
共30条数据 1 3 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐