Date currentDate = new Date(); int month = currentDate.getMonth(); System.out.println("Current month: " + month); // output: Current month: [month number]
Date specificDate = new Date(121, 3, 15); // 15th April 2021 int month = specificDate.getMonth(); System.out.println("Month of specific date: " + month); // output: Month of specific date: 3In this example, we created a new Date object for a specific date (15th April 2021) and then used getMonth() to retrieve the month number (which is 3 as April is the 4th month). The Date class and its getMonth() method belong to the java.util package library.