java - DateTime.plusMinutes(..) 返回分钟 -1

标签 java jodatime

我在使用 JodaTime 时遇到问题。这是我的方法:

public double calculateTimeDifference(String startedAt) {
    DateTime cet = new DateTime(DateTimeZone.forID("CET"));

    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss'Z'");
    DateTime convertedStartedAt = formatter.parseDateTime(startedAt);

    Period period = new Interval(cet, convertedStartedAt).toPeriod();
    int minutes = period.getMinutes();

    return minutes;
}

我有一个测试,时间增加了 30 分钟:

@Test
public void testTimeDifference() {
    DateTime testtime = new DateTime(DateTimeZone.forID("CET")).plusHours(2);
    testtime = testtime.plusMinutes(30);

    // Format for input
    DateTimeFormatter cet = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
    // Parsing the date
    DateTime requestedFormat = cet.parseDateTime(testtime.toString());
    // Format for output
    DateTimeFormatter requestedTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss'Z'");

    double time = carService.calculateTimeDifference(requestedTime.print(requestedFormat));

    assertEquals(30, time, 0.0);
}

但是当我运行这个时,输出是:

Expected : 30.0
Actual : 29.0

最佳答案

原因是您生成了两倍的当前日期和时间: 一旦到这里:

    DateTime testtime = new DateTime(DateTimeZone.forID("CET")).plusHours(2);

这里:

    DateTime utc = new DateTime(DateTimeZone.forID("CET"));

因此,实际差异是 29 分 59 秒和 360 毫秒(在我的测试中),四舍五入为 29 分钟。

关于java - DateTime.plusMinutes(..) 返回分钟 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53517298/

相关文章:

java - Maven:执行wsgen时找不到tools.jar

java - 如何解释 Eclipse Memory Analyzer( Camel route 的内存泄漏)

java - 创建一个日期列表,其值为 "change of condition"

java - 重新打开应用程序时恢复计时器

java - 在java中年龄计算返回错误值

java - 使用 HtmlUnit 登录 Gmail

java - 开机完成后需要立即启动app

java - Google App Engine Blobstore 存储 Blob 但生成无效 key !?我的代码有什么问题?

java - JodaTime setCurrentMillisFixed(millis) 没有像想象的那样工作

jodatime - Joda-Time 的运行时间