How to display date of a current month with the month and year in Java?

前端 未结 2 777
天命终不由人
天命终不由人 2021-01-21 21:19

How to display the date, month, and year of a particular month in for loop dynamically in Java?

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-21 21:34

    This demonstrates briefly some of the basics of the SimpleDateFormat and GregorianCalendar classes in Java. It was the best I could do based on your question.

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

提交回复
热议问题