Java Data Type How to - Display date of a current month with the month and year








Question

We would like to know how to display date of a current month with the month and year.

Answer

import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
/*from   ww  w . j  a  v a 2s.c o  m*/
public class Main {
    public static void main(String[] args) {
        int year = 2015;
        int month = 4;

        SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");

        GregorianCalendar calendar = new GregorianCalendar(year, month, 1);

        while (calendar.get(GregorianCalendar.MONTH) == month) {
            String dateString = format.format(calendar.getTime());
            System.out.println(dateString);

            calendar.add(GregorianCalendar.DATE, 1);
        }
    }
}

The code above generates the following result.