Recently, my android app needed to get the current date and time from its system. 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.
Android Get Current Date or Time |
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);
The output of the code above is:
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.
You should read more about the Android's Calendar Class and SimpleDateFormat Class. Thanks for sharing your thoughts about getting the current date and time in Android!
The Code of a Ninja Resources
For FREE programming tutorials, click the red button below and subscribe! :)
website