使用joda时间的剩余年,月,日(Android)

时间:2016-08-03 17:00:42

标签: java android

我想在两个日期之间获得剩余的年,月和日: 所以我用Joda Time这样做了:

DateTime endDate  = new DateTime(2018,12,25,0,0);   
DateTime startDate = new DateTime();
Period period = new Period(startDate,endDate,PeriodType.yearMonthDay());

PeriodFormatter formatter = new PeriodFormatterBuilder().appendYears().appendSuffix(" Year ").
            appendMonths().appendSuffix(" Month ").appendDays().appendSuffix(" Day ").appendHours()..toFormatter();

String time = formatter.print(period);

这给了我字符串时间:2年4月22日

但是,我想要每个剩余年,月,日的数量的整数值。 所以,而不是" 2年4月22日",我想设置我的变量:

int year = 2
int month = 4
int day = 22

有没有办法分别获取这些值而不是获得一个字符串?非常感谢! :)

2 个答案:

答案 0 :(得分:1)

我有一次相同的要求,这里是代码片段

    LocalDate d=LocalDate.of(yy,mm,dd);
    LocalDate d2=LocalDate.of(yy, mm, dd);
    Period p=Period.between(d, d2);
    long day,month,year;
    day=p.getDays();
    month=p.getMonths();
    year=p.getYears();
    System.out.println(day+" : "+month+" : "+year);

答案 1 :(得分:0)

调用DateTime类提供的方法并简单地减去它们。多年来的一个例子如下:

int year = (int) dateTime#year#getField() - (int) dateTime2#year#getField()

UNTESTED代码!!我稍后会对此进行调查,但总体思路是相同的,获取字段信息然后将其减去以获得值