简体   繁体   English

Joda-Time将天数转换为月数

[英]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 . 如何使用Joda-Time将天数转换为月数和天数。 For example, when I have 33 days, it should display 1 month and 2 days. 例如,当我有33天时,它应该显示1个月零2天。

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. 您可以为此使用org.joda.time.Period类。
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). 尝试创建一个十进制小数表示月份对我来说是没有意义的,因为月份的天数不同(28、29、30、31)。

ISO 8601 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 . 明智的ISO 8601标准定义了一种文本方式,以月和日为单位表示时间跨度,称为“ 持续时间” Joda-Time has a class for this purpose called Period . 为此, Joda-Time有一个叫做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. 有关使用Period类的示例,请参见Ilya关于此问题的其他答案

ISO Duration ISO持续时间

The textual format is PnYnMnDTnHnMnS where P means "Period" and the T separates the date portion from time portion. 文本格式为PnYnMnDTnHnMnS ,其中P表示“句点”,而T则将日期部分与时间部分分开。 The other parts are optional. 其他部分是可选的。 One month and two days would be P1M2D . 一个月P1M2D两天就是P1M2D The Joda-Time Period class both parses and generates such strings. Joda-Time Period类既解析并生成此类字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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