java - 包括本月在内的 future 六个月 list

标签 java scala datetime

我可以用这种格式获取当前月份 通过

val dateFormat: SimpleDateFormat = new SimpleDateFormat("YYYYMM")
dateFormat.format(new Date())//201408

但是怎么得到

List(201408,201409,201410,201411,201412,201501)

最佳答案

(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)));
}

使用日历:

// 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);
}

关于java - 包括本月在内的 future 六个月 list ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25197322/

相关文章:

python - 在 Python 2.5 中用微秒解析日期时间字符串

java - Gurobi 和 java 和 empty 解决方案

java - 使用 JDOM 解析 XML 文件,出现错误 StackOverflowError

java - InheritableThreadLocal 值未被 ExecutorService 线程继承

function - 自定义 scala 递归预防机制的改进

scala - Scala中:::(三元冒号)的用途是什么

java - spring rest 处理空请求体(400 Bad Request)

java - JPanel 中的内容不会出现

java - 无法在 Android Studio 上将 DateTime 插入 SQLite

python - 在 Python 中将年/月/日转换为年中的某天