2

我想在 android 中计算两次的差异:例如 Date now 和 1356033600000 ->timestamp from location.getTime() 之间的差异

= 2 分钟前

我只需要几分钟!我该怎么做?

我通过 json 获得客户端时间。客户时间 = 1356033600000

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

3 回答 3

1

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

于 2012-12-20T20:23:44.897 回答
1

在 Android / Java 中,时间通常以毫秒为单位计算,您可以使用现有的常量来帮助您执行这个简单的检查:

//                                  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
}

这是您使用时的常见检查LocationManager#getLastKnownLocation(),只需确保location在调用之前不为空即可location.getTime()

于 2012-12-20T20:22:56.163 回答
0

这是我在自己的应用程序中使用的代码片段:

                    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;
                    }

您可以轻松更改代码以比较分钟数。

于 2012-12-20T20:14:51.593 回答