我可以用这种格式获得当前月份 由
val dateFormat: SimpleDateFormat = new SimpleDateFormat("YYYYMM")
dateFormat.format(new Date())//201408
但是如何获得
List(201408,201409,201410,201411,201412,201501)
答案 0 :(得分:3)
(Java语法,但我确定你可以很容易地将它改为Scala。)
按优先顺序降序......
使用Java 8:
// TODO: Which time zone are you interested in?
YearMonth yearMonth = YearMonth.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
List<String> dates = new ArrayList<>();
for (int i = 0; i < 6; i++) {
dates.add(formatter.format(yearMonth.plusMonths(i)));
}
与Joda时间:
// TODO: Which time zone are you interested in?
YearMonth yearMonth = new YearMonth();
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMM");
List<String> dates = new ArrayList<>();
for (int i = 0; i < 6; i++) {
dates.add(formatter.print(yearMonth.plusMonths(i)));
}
使用Calendar
:
// TODO: Which time zone are you interested in?
Calendar calendar = Calendar.getInstance();
DateFormat format = new SimpleDateFormat("yyyyMM");
List<String> dates = new ArrayList<>();
for (int i = 0; i < 6; i++) {
dates.add(format.format(calendar.getTime()));
calendar.add(Calendar.MONTH, 1);
}
答案 1 :(得分:1)
在 scala 中,使用Joda Time:
val yearMonth = new YearMonth();
val formatter = DateTimeFormat.forPattern("yyyyMM");
val dates = (0 to 5).map {
i=>formatter.print(yearMonth.plusMonths(i)).toInt
}.toList