【问题标题】:Joda Time how to calculate how much time left?Joda Time如何计算还剩多少时间?
【发布时间】:2015-11-05 17:15:59
【问题描述】:

在我的这部分代码中,我希望 Joda Time 计算并显示距离下一个生日还剩多少时间。所以年份应该在生日时改变

DateTime startDate = DateTime.now();
DateTime endDate = new DateTime(x,m110,d110,h120,min120);
Period period = new Period(startDate, endDate, PeriodType.dayTime());
textView3.setText(formatter.print(period));
PeriodFormatter formatter = new PeriodFormatterBuilder()
                    .appendMonths().appendSuffix(".")
                    .appendDays().appendSuffix(" ")
                    .appendHours().appendSuffix(":")
                    .appendMinutes().appendSuffix(":")
                    .appendSeconds()
                    .toFormatter();

x 这里是年,m110,d110,h120,min120 - 月、日、小时和分钟。我应该写什么而不是“x”,这样它就可以计算每年还剩下多少时间,而不是一次。还有一个问题。例如,当它是 3 小时 4 分钟时,我应该怎么做才能显示“03:04:00”而不是“3:4:”(它也只是不显示 0)

【问题讨论】:

    标签: java jodatime periodformatter


    【解决方案1】:

    x 的值取决于今年是否已经过生日。您可以在当年的同一天和同一月使用DateTime.before 方法进行检查:

    DateTime startDate = DateTime.now();
    int year = startDate.getYear();
    DateTime endDate = new DateTime(year,m110,d110,h120,min120);
    if (endDate.isBefore(startDate)) // birthday happend already this year?
        endDate = endDate.plusYears(1); // then the next one is in the next year
    

    关于你的第二个问题: 您可以建议builder 创建一个始终使用printZeroAlways() 打印零的格式化程序。要让格式化程序打印至少两位数字,您可以使用 minimumPrintedDigits 方法:

       PeriodFormatter formatter = new PeriodFormatterBuilder()            
            .minimumPrintedDigits(0)
    
            .appendMonths().appendSuffix(".")
            .printZeroAlways()
            .appendDays().appendSuffix(" ")
    
            .minimumPrintedDigits(2)
    
            .appendHours().appendSuffix(":")
            .appendMinutes().appendSuffix(":")
            .appendSeconds()
            .toFormatter();
    

    请注意,这些方法仅适用于在调用方法后添加的字段。此外,该值可能会随着构建器的创建而多次更改。

    【讨论】:

      猜你喜欢
      • 2011-06-26
      • 1970-01-01
      • 1970-01-01
      • 2011-10-14
      • 2017-01-11
      • 1970-01-01
      • 2011-01-11
      • 1970-01-01
      • 2022-06-24
      相关资源
      最近更新 更多