码迷,mamicode.com
首页 > 移动开发 > 详细

Get current time and date on Android

时间:2014-05-27 17:13:56      阅读:512      评论:0      收藏:0      [点我收藏+]

标签:android   c   class   code   java   http   

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,布布扣,bubuko.com

Get current time and date on Android

标签:android   c   class   code   java   http   

原文地址:http://www.cnblogs.com/savagemorgan/p/3753063.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!