Get Current Date and Time in Android using Two Classes
Recently, I needed to get current date and time in android. 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 and useful for you.
A simple outline of this post:
1.0 Using the Calendar Class
2.0 Using the SimpleDateFormat Class
3.0 My Thoughts
4.0 Helpful Comments
1.0 Using the Calendar Class
Here’s how to get android date and time using the Calendar Class.
The output of the code above is:
2.0 Using the SimpleDateFormat Class
And here’s how to get it using SimpleDateFormat Class.
SimpleDateFormat code output will be:
3.0 My Thoughts
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!
4.0 Helpful Comments
I love reading useful comments and so we will highlight them by including it in our post. Thanks Kovica and Charuta!
According to Kovica:
You didn’t find any bugs, because if you look closely at the docs for the java.util.Calendar class, you’ll see that JANUARY = 0 http://developer.android.com/reference/java/util/Calendar.html#JANUARY), so JUNE = 5 http://developer.android.com/reference/java/util/Calendar.html#JUNE)
You could use the Time class, it’s a faster implementation of Calendar class. http://developer.android.com/reference/android/text/format/Time.html
How about you, do you have any other solution or thought about getting current date and time in Android? Drop it in the comments section below! Thanks!
Источник