简体   繁体   中英

Joda-Time convert days to months and days

How can I convert the number of days to number of months and days using Joda-Time . For example, when I have 33 days, it should display 1 month and 2 days.

public static void main(String[]args) 
   {        
        Calendar calendar = new GregorianCalendar();

         int years = calendar.get(Calendar.YEAR);
         int month = (calendar.get(Calendar.MONTH))+1;
         int day = calendar.get(Calendar.DATE);

         DateTime startDate = new DateTime(years, month, day, 0, 0, 0, 0);
         DateTime endDate = new DateTime(2014, 7, 3, 0, 0, 0, 0);

         Days d = Days.daysBetween(startDate, endDate);

         int days = d.getDays();
         int t = 1000 * 60 * 60 *24;
         int days = days/t;
         System.out.println(days);
}

You can use class org.joda.time.Period for this.
Example:

  Period p = new Period(startDate, endDate, PeriodType.yearMonthDayTime());
  System.out.println(p.getMonths()); 
  System.out.println(p.getDays()); 

Trying to create a decimal fraction number to represent months makes no sense to me, as months have different numbers of days (28, 29, 30, 31).

ISO 8601

The sensible ISO 8601 standard defines a textual way to represent a span of time in terms of months and days, called Durations . Joda-Time has a class for this purpose called Period . Forgive the mismatch in terms, as there is no standard definition of date-time terminology yet.

For an example of using the Period class, see this other answer by Ilya on this question.

ISO Duration

The textual format is PnYnMnDTnHnMnS where P means "Period" and the T separates the date portion from time portion. The other parts are optional. One month and two days would be P1M2D . The Joda-Time Period class both parses and generates such strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM