【问题标题】:Joda Time minutes in a duration or interval持续时间或间隔中的 Joda Time 分钟
【发布时间】:2012-02-09 16:20:24
【问题描述】:

我有这个简单的代码:

DateTime date = new DateTime(dateValue);
DateTime currentDate = new DateTime(System.currentTimeMillis());

System.out.println("date: " + date.toString());
System.out.println("currentDate: " + currentDate.toString());

Period period = new Period(currentDate, date);
System.out.println("PERIOD MINUTES: " + period.getMinutes());
System.out.println("PERIOD DAYS: " + period.getDays());

Duration duration = new Duration(currentDate, date);
System.out.println("DURATION MINUTES: " + duration.getStandardMinutes());
System.out.println("DURATION DAYS: " + duration.getStandardDays());

我试图简单地找出两个随机日期之间的天数和分钟数。

这是这段代码的输出:

date: 2012-02-09T00:00:00.000+02:00
currentDate: 2012-02-09T18:15:40.739+02:00
PERIOD MINUTES: -15
PERIOD DAYS: 0
DURATION MINUTES: -1095
DURATION DAYS: 0

我猜我做错了什么,我只是看不到什么。

【问题讨论】:

    标签: java date


    【解决方案1】:

    问题在于您没有在周期构造函数中指定周期类型 - 因此它使用默认值“年、月、周、日、小时、分钟、秒和毫秒”。您只看到 15 分钟,因为您没有要求几个小时,这将返回 -18。

    如果你只想要天和分钟,你应该指定:

    PeriodType type = PeriodType.forFields(new DurationFieldType[] {
                                               DurationFieldType.days(),
                                               DurationFieldType.minutes()
                                           });
    
    Period period = new Period(currentDate, date, type);
    // Now you'll just have minutes and days
    

    了解DurationPeriod 之间的区别很重要,Duration 是“一定的毫秒数,可以根据不同的单位获取”,Period 实际上是一组字段类型(分钟)的映射, 月, 天等) 到值。一个时期内没有一个单一的时间价值——它是价值的集合。

    【讨论】:

    • @LouisWasserman:我在将 Joda Time 移植到 .NET 时遇到了一些特殊情况,所以我可能比大多数人更了解它:)
    【解决方案2】:

    看起来它工作得很好,你需要做的就是交换datecurrentDate

    Period period = new Period(date, currentDate);
    

    【讨论】:

    • 我认为 OP 担心“分钟”的一种观点是给 15,而另一种观点是给 1095...
    猜你喜欢
    • 2011-06-26
    • 2012-08-15
    • 2015-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-15
    相关资源
    最近更新 更多