Get current time and date on Android

You could use:

Calendar c =Calendar.getInstance();int seconds = c.get(Calendar.SECOND);

There are plenty of constants in Calendar for everything you need. Edit: Calendar class documentation

#########

You can use android.text.format.Time:

Time now =newTime();
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.

 

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

SimpleDateFormat sdf =newSimpleDateFormat("yyyyMMdd_HHmmss");String currentDateandTime = sdf.format(newDate());


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 =newTime(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.

 

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 =newDate(System.currentTimeMillis());

And as mentioned by others to create a time

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


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

DateFormat df =newSimpleDateFormat("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

http://stackoverflow.com/questions/5369682/get-current-time-and-date-on-android

Get current time and date on Android,,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。