Wednesday, 27 June 2012

Getting Android Device Current Date and Time

Recently, my Android App needed to get the value of the device, or system, date and time. I found two ways of doing it. They are by using the Calendar class and SimpleDateFormat class. So let's see what method will be more simple for you.


Getting Android Device Current Date and Time
What time is it?

tv = (TextView) this.findViewById(R.id.thetext);
        
//using Calendar class
Calendar ci = Calendar.getInstance();

String CiDateTime = "" + ci.get(Calendar.YEAR) + "-" + 
     (ci.get(Calendar.MONTH) + 1) + "-" +
     ci.get(Calendar.DAY_OF_MONTH) + " " +
     ci.get(Calendar.HOUR) + ":" +
     ci.get(Calendar.MINUTE) +  ":" +
     ci.get(Calendar.SECOND);
        
tv.append( CiDateTime + "\n" );
        
//using SimpleDateFormat class
SimpleDateFormat sdfDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
String newtime =  sdfDateTime.format(new Date(System.currentTimeMillis()));
        
tv.append(newtime);

I have the output of the code above as:
2011-6-9 7:0:56
2011-06-09 19:00:56

As you can see, using the calendar class seemed like it require us to code more. Also, I think I found a bug. My device calendar settings are correct. It is month of June, so ci.get(Calendar.MONTH) must return "6" but it returns "5" so I had to add "1" to make the output correct.


In my case, I used the SimpleDateFormat class since I don't really have to synchronize it. It is easy to format - you can just use its time pattern strings (in our example "yyyy-MM-dd HH:mm:ss"). But please be aware that it was said in the docs that SimpleDateFormat is NOT thread safe when it comes to Synchronization.

For more info and resources:
http://developer.android.com/reference/java/util/Calendar.html
http://developer.android.com/reference/java/text/SimpleDateFormat.html

0 comments:

Post a Comment

Internet-PublicLab. Powered by Blogger.