【问题标题】:Joda Time complex operations on timeJoda Time 复杂操作准时
【发布时间】:2013-06-23 07:02:06
【问题描述】:

我想在我的项目中使用 Joda Time。我很想知道我是否知道如何使用它。 首先 - 我想创建一个我初始化的进度条,然后每秒计算它的值 - 它显示完成过程的剩余时间。

在初始化期间,我只有格式为“HH:mm:ss”(偶尔为“D 天 HH:mm:ss”)的字符串,表示剩余时间和百分比 - 进度条的初始状态。这就是我所拥有的。

现在我想创建一个代表任务完成时刻的 DateTime 对象。

PeriodFormatter timeFormatter = new PeriodFormatterBuilder()
        .appendHours().appendSeparator(":").appendMinutes()
        .appendSeparator(":").appendSeconds().toFormatter();
DateTime endDate_ = new Date();
Period periodLeft = null;
String[] parsedInput = timeLeft.split(" ");
if (parsedInput != null) {
    switch (parsedInput.length) {
    case 1: {
        periodLeft = timeFormatter.parsePeriod(parsedInput[0]);
        endDate_.plus(periodLeft);
        break;
    }
    case 3: {
        periodLeft = timeFormatter.parsePeriod(parsedInput[2]);
        periodLeft.plusDays(Integer.parseInt(parsedInput[0]));
        endDate_.plus(periodLeft);
        break;
    }
    default:
        break;
    }
}

据我所知,我有我想要的,对吧?现在我想计算过程的总持续时间。这就是为什么我将此时间段转换为毫秒并根据进度计算总持续时间:

long duration_ = (periodLeft.toStandardDuration().getMillis() * 100) / (progress == 0 ? 1 : progress);

现在我必须实现一个基于当前时间返回进程实际状态的方法。我怎样才能做到这一点?我知道持续时间,所以我可以得到开始日期时间。然后我可以简单地将当前日期与开始日期和计数百分比进行比较:(now - start)/duration_ * 100。但是我怎样才能得到开始日期?

【问题讨论】:

    标签: parsing jodatime


    【解决方案1】:

    Jodatime 非常易于使用,您无需使用格式化程序填充代码即可获得所需的内容。无论您测量的过程是什么,都必须在您的代码中的某个时间点开始,而这正是您应该记下开始时间的地方。试试这样的。

     DateTime startTime = DateTime.now();
     DateTime endTime = DateTime.now();
     endTime.plusSeconds(50);
    
    
     //Write code for your application.
     //....
     Thread.sleep(3000);
    
     //Calculate your percentage.
     double remainingPercentage =  (  DateTime.now().getMillis() - startTime.getMillis()) / ( endTime.getMillis() - DateTime.now().getMillis() )*100 ;
    
    //Then output the date using the string method.
     endTime.toString("MMM dd yy ");
    

    【讨论】:

    • 这个解决方案是错误的。正如我所说 - 我没有开始时间。即使我的应用程序关闭,进程也会开始。我解决了我的问题。
    • @user1849493 那么你在哪里可以找到开始时间呢?如果你不知道它是什么时候开始的,那么你就不能可靠地说你有一个可靠的百分比。虽然就像你说你解决了它。这很好。
    【解决方案2】:

    好的。我设法解决了!计算进度的函数现在稍微修改为:

    if (progress == 0)
        duration_ = periodLeft.toStandardDuration().getMillis();
    else
        duration_ = (long) ((periodLeft.toStandardDuration().getMillis() * 100) / (double) (100 - progress));
    

    我接下来要做的是将我的 progressBar 最大值设置为 duration_ 并每隔一秒设置一次进度值以显示到:

    new Period(startDate_, DateTime.now())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多