2015-11-05 57 views
0

在我的代码的这一部分,我希望乔达时间计算并显示下一个生日还剩下多少时间。因此,今年要改变的生日乔达时间如何计算剩下多少时间?

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),我应该怎么做?

回答

0

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(); 

注意,这些方法仅适用于域方法的调用后添加。此外,该值可能会随着建造者的创作而多次改变。