【问题标题】:How to add part of time in Android如何在Android中添加部分时间
【发布时间】:2011-04-12 09:08:39
【问题描述】:

我有一个代码返回一个字符串 (HH:mm)。

SimpleDateFormat curFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
        java.util.Date dateObj;
        try {
            dateObj = curFormater.parse(start);

            SimpleDateFormat postFormater = new SimpleDateFormat("HH:mm"); 
            String newDateStr = postFormater.format(dateObj); 
            startView.setText(newDateStr);
            Emission_start = newDateStr;
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            Log.d(" * Error", e.toString());
        }

效果很好……但现在我想:

  1. 添加 x(动态提供)分钟(x = 从 5 到 1000 分钟)并转换为时间(例如时间:3:45,增加 25 分钟,转换为时间 4:10)
  2. 获取当前时间并计算当前时间与步骤 1 (4:10) 中的时间之间的差异
  3. 以分钟为单位获取时差(从第 2 步开始)!

感谢您的帮助!

【问题讨论】:

    标签: android date time


    【解决方案1】:

    我还没有测试过,但是这样的东西应该可以工作:

    1. long newDate = dateObj.getTime() + (x * 60 * 1000)

    2. long diff = System.currentTimeMillis() - newDate

    3. double diffInMins = diff / (60.0 * 1000.0)

    【讨论】:

    • 这样的东西我已经试过了..(也试过这个)结果是错误的......但我不知道为什么......
    • 经过一些测试,我发现第 3 点或第 2 点不正确... newDate 没问题 ...
    • Wups ...这是由于模拟器错误...发布错误的当前时间..修复了!感谢您的帮助!
    【解决方案2】:
    1. 使用日历

      日历 calInstance = new GregorianCalendar(); calInstance.setTime(dateObj);

    然后添加你想要的任何片段,几分钟就可以了

    calInstance.add(Calendar.MINUTE, XX)
    

    使用您的格式化程序进行转换

    postFormatter.format(calInstance.getTime());
    
    1. 微不足道

    2. 也可以轻松计算以分钟为单位的差异

      long diffInMins = (currTimeInMillis - calInstance.getTimeInMillis())/(1000 * 60);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-19
      • 1970-01-01
      • 1970-01-01
      • 2018-08-24
      • 2016-12-22
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多