Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Compare time in this format `yyyy-mm-dd hh:mm:ss` to the current moment

I want to get the current time on the device in the format: 2013-10-17 15:45:01 ?

The server sends me the date of an object in the format above as a string. Now i want to get the phones current time and then check if there is a difference of say more than 5 minutes?

So A: How can i get the devices current time in this fomat: 2013-10-17 15:45:01

B how can I work out the difference between the two.

like image 842
Zapnologica Avatar asked Oct 17 '13 21:10

Zapnologica


People also ask

How do I display the current time on my Android?

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. In the above code, we have given text view, it going to print the current date on the window manager.

What is SSSZ in date format?

Dates are formatted using the following format: "yyyy-MM-dd'T'hh:mm:ss'Z'" if in UTC or "yyyy-MM-dd'T'hh:mm:ss[+|-]hh:mm" otherwise. On the contrary to the time zone, by default the number of milliseconds is not displayed. However, when displayed, the format is: "yyyy-MM-dd'T'hh:mm:ss.


1 Answers

You can use SimpleDateFormat to specify the pattern you want:

new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new java.util.Date())

However, if you just want to know whether the time difference is within a certain threshold, you should probably just compare long values. If your threshold is 5 minutes, then this is 5 * 60 * 1000 milliseconds so you can use the same SimpleDateFormat by calling it's parse method and check the long values.

Example:

new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2013-10-13 14:54:03").getTime()
like image 140
ATG Avatar answered Oct 13 '22 21:10

ATG