【问题标题】:Joda Time Manipulation get 15th and last day of monthJoda Time Manipulation 获得每月的第 15 天和最后一天
【发布时间】:2015-04-01 15:04:07
【问题描述】:

如何循环获取 Joda 时间每月的第 15 天和最后一天?

代码如下:

DateTime initDate = new DateTime(2015,1,31,0,0);

for(int i = 0; i > 4; i++){
  initDate = initDate.plusDays(15);

   System.out.println(initDate.toString("yyyy-MM-dd");
}

我只希望结果是这样的:

2015-2-15
2015-2-28
2015-3-15
2015-3-30

【问题讨论】:

标签: java datetime jodatime


【解决方案1】:
for(int i = 0; i < 4; i++){ 
            initDate = initDate.plusMonths(1);
            initDate = initDate.withDayOfMonth(15);
            System.out.println(initDate.toString("yyyy-MM-dd"));
            System.out.println(initDate.dayOfMonth().withMaximumValue().toString("yyyy-MM-dd"));
        }

类似的东西?

【讨论】:

  • 可能不会像您认为的那样做。毕竟,2 月的最大值是 29 日,只有大约 25% 的时间是正确的。
  • 谢谢先生。这真的很有帮助。
  • @EdwinBuck 答案是正确的。 (优雅的)方法withMaximumValue() 取决于上下文,因为您可以轻松地验证自己。
【解决方案2】:

循环很好,但您可以直接添加一个月而不是添加天数(查看http://joda-time.sourceforge.net/key_period.htmlhttp://joda-time.sourceforge.net/apidocs/org/joda/time/Months.html) 而不是得到你可以使用的本月的最后一天

yourcurrentDate.dayOfMonth().withMaximumValue()

【讨论】:

    【解决方案3】:

    您无法通过添加固定天数来获得该月的最后一天,因为所有月份的天数都不相同。

    相反,像这样使用你的循环

    for (each month) {
       set the month appropriately (set not add)
       get the 15th day of this month (set not add)
       print the 15th day
       set the next month
       set the 1st day of the "next" month
       subtract a day
       print the "last" day
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-01
      • 2014-03-22
      相关资源
      最近更新 更多