sarahsdev
sarahsdev

Reputation: 177

android: How can I calculate a time span

I want calculate the difference of two times in android: e.g. the difference between Date now and 1356033600000 ->timestamp from location.getTime()

= 2 Minutes ago

I only need the minutes! How can I do it?

I get clienttime via json. clienttime = 1356033600000

String clienttime = e.getString("clienttime");
long mTime = (System.currentTimeMillis() - Long.valueOf(clienttime).longValue()) / (60 * 1000);

Upvotes: 2

Views: 3295

Answers (3)

Sam
Sam

Reputation: 86948

Time is typically calculated in milliseconds in Android / Java, you can use existing constants to help you perform this simple check:

//                                  now            minus           two minutes
if(location.getTime() > System.currentTimeInMillis() - 2 * DateUtils.MINUTE_IN_MILLIS) {
    // The location is less than two minutes old 
} 
else {
    // The location is possibly stale
}

This is a common check when you are using LocationManager#getLastKnownLocation(), just make sure location is not null before calling location.getTime().

Upvotes: 1

Philip Pearl
Philip Pearl

Reputation: 1533

(System.currentTimeMillis() - location.getTime()) / (60 * 1000)

Upvotes: 1

ObAt
ObAt

Reputation: 2387

This is a code snippet wich I'am using in my own applications:

                    String oldDate = xmlResults[3]; //insert old dateTime in the following format: yyyy-MM-dd HH:mm:ss
                    int myValue = 15; //Check if difference is between 15 hours

                    // Date Time Format
                    SimpleDateFormat formatter = new SimpleDateFormat(
                            "yyyy-MM-dd HH:mm:ss");

                    // Convert Date to Calendar
                    Date xmlDate = formatter.parse(oldDate);
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(xmlDate);

                    Calendar today = Calendar.getInstance();

                    // Check difference
                    long diff = today.getTimeInMillis() - cal.getTimeInMillis();

                    long hours = diff / 3600000; // 1000ms * 60sec * 60hours ->
                                                    // total hours

                    if (hours < myValue && hours >= 0) {
                        // Login is successful, return true
                        return true;
                    } else {
                        return false;
                    }

You can easily change to code to compare minuts.

Upvotes: 0

Related Questions