小编典典

如何在Java中用月份和年份显示当前月份的日期?

java

如何在Java中动态显示for循环中特定月份的日期,月份和年份?


阅读 308

收藏
2020-11-26

共1个答案

小编典典

这简要演示了Java SimpleDateFormatGregorianCalendar类的一些基础知识。根据您的问题,这是我能做的最好的事情。

import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;

public class Main {
    public static void main(String[] args) {
        int year = 2012;
        int month = 4;

        /* The format string for how the dates will be printed. */
        SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");

        /* Create a calendar for the first of the month. */
        GregorianCalendar calendar = new GregorianCalendar(year, month, 1);

        /* Loop through the entire month, day by day. */
        while (calendar.get(GregorianCalendar.MONTH) == month) {
            String dateString = format.format(calendar.getTime());
            System.out.println(dateString);

            calendar.add(GregorianCalendar.DATE, 1);
        }
    }
}
2020-11-26