首页 > 解决方案 > 递增月份

问题描述

我有一个可以保存一个月的字符串。

String mon = "January";

nextMon现在,下个月应该有另一个字符串。也就是说,nextMon应该是"February"if monis "January"

mon从函数中获取字符串,所以它必须自动发生。

请告诉我最简单的方法。

标签: javastringdate

解决方案


正如 Slaw 所说,使用Month一年中的一个月,而不是字符串。将你的字符串解析成Month这样的:

    DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MMMM", Locale.ENGLISH);

    String monthAsString = "January";

    Month mon = monthFormatter.parse(monthAsString, Month::from);
    System.out.println(mon);

到目前为止的输出是:

一月

增加。只需添加 1:

    mon = mon.plus(1);
    System.out.println(monthFormatter.format(mon));

二月


推荐阅读