创建日期范围Scala,Joda,Java
问题内容:
我花了几个小时试图使下一部分代码正常工作。
import org.joda.time.{DateTime, Period}
def dateRange(from: DateTime, to: DateTime, step: Period): Iterator[DateTime] =Iterator.iterate(from)(_.plus(step)).takeWhile(!_.isAfter(to))
val range = {
dateRange(new DateTime(2012, 06, 30).minusYears(5), new DateTime(2000, 06, 30),new Period.months(6))
}
我正在尝试建立一个日期范围数组,以6个月的增量从2000到2012。我面临的问题是以下错误。
Exception in thread "main" java.lang.IllegalArgumentException: No instant converter found for type: scala.Tuple3
at org.joda.time.convert.ConverterManager.getInstantConverter(ConverterManager.java:165)
at org.joda.time.base.BaseDateTime.<init>(BaseDateTime.java:169)
at org.joda.time.DateTime.<init>(DateTime.java:241)
at tester.MomentumAlgo$class.$init$(MomentumAlgo.scala:154)
at tester.RunMomentumAlgo$$anon$1.<init>(RunMomentumAlgo.scala:86)
at tester.RunMomentumAlgo$.main(RunMomentumAlgo.scala:86)
at tester.RunMomentumAlgo.main(RunMomentumAlgo.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
我似乎与Period.months()的最后一部分有关,但是我不知道如何解决。我不知道Tuple3错误。
如果有人可以给我其他解决方案,那也很好。我想要一个从2000年到2012年的日期列表,每6个月一次。
欢迎任何问题。我以为这是一段普通的代码,但是网上并没有太多内容。
提前致谢。
问题答案:
解决方法是定义这样的日期:
val date = new DateTime().withYear(2013).withMonthOfYear(7).withDayOfMonth(16)
然后,REPL中的整个序列变为:
scala> import org.joda.time.{DateTime, Period}
import org.joda.time.{DateTime, Period}
scala> def dateRange(from: DateTime, to: DateTime, step: Period): Iterator[DateTime] =Iterator.iterate(from)(_.plus(step)).takeWhile(!_.isAfter(to))
dateRange: (from: org.joda.time.DateTime, to: org.joda.time.DateTime, step: org.joda.time.Period)Iterator[org.joda.time.DateTime]
scala> val from = new DateTime().withYear(2012).withMonthOfYear(6).withDayOfMonth(30).minusYears(5)
from: org.joda.time.DateTime = 2007-06-30T21:46:05.536-07:00
scala> val to = new DateTime().withYear(2000).withMonthOfYear(6).withDayOfMonth(30)
to: org.joda.time.DateTime = 2000-06-30T21:46:26.186-07:00
scala> val range = dateRange(from, to, new Period().withMonths(6))
range: Iterator[org.joda.time.DateTime] = non-empty iterator
scala> range.toList
res4: List[org.joda.time.DateTime] = List(
2000-06-30T21:46:26.186-07:00,
2000-12-30T21:46:26.186-08:00,
2001-06-30T21:46:26.186-07:00,
2001-12-30T21:46:26.186-08:00,
2002-06-30T21:46:26.186-07:00,
2002-12-30T21:46:26.186-08:00,
2003-06-30T21:46:26.186-07:00,
2003-12-30T21:46:26.186-08:00,
2004-06-30T21:46:26.186-07:00,
2004-12-30T21:46:26.186-08:00,
2005-06-30T21:46:26.186-07:00,
2005-12-30T21:46:26.186-08:00,
2006-06-30T21:46:26.186-07:00,
2006-12-30T21:46:26.186-08:00)
另外,如我的评论中所述,我无法重现此内容。似乎在REPL和编译器中行为是不同的。