【问题标题】:android: How can I calculate a time spanandroid:如何计算时间跨度
【发布时间】:2012-12-20 20:12:09
【问题描述】:

我想在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);

【问题讨论】:

    标签: android datetime


    【解决方案1】:

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

    【讨论】:

    • 我尝试这样但它不起作用:我通过 json 获取客户端时间。我编辑我的帖子
    • 您的时钟是否同步并使用相同的时区?
    【解决方案2】:

    时间在 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.getTime() 之前确保location 不为空即可。

    【讨论】:

      【解决方案3】:

      这是我在自己的应用程序中使用的代码 sn-p:

                          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-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-16
        • 2016-05-22
        • 2010-09-13
        • 2013-01-21
        • 1970-01-01
        相关资源
        最近更新 更多