Java: Get month Integer from Date
To get the month integer from a java.util.Date
object in Java, you can use the getMonth()
method of the java.util.Calendar
class.
Here is an example of how you can use the getMonth()
method to get the month integer from a Date
object:
import java.util.Calendar;
import java.util.Date;
public class Main {
public static void main(String[] args) {
// Create a Date object
Date date = new Date();
// Get the Calendar instance
Calendar cal = Calendar.getInstance();
// Set the Calendar time to the Date object
cal.setTime(date);
// Get the month integer (0-based)
int month = cal.get(Calendar.MONTH);
// Print the month integer
System.out.println("Month: " + month);
}
}
This code creates a Date
object, gets the Calendar
instance, sets the Calendar
time to the Date
object, and uses the get()
method with the Calendar.MONTH
constant to get the month integer. It then prints the month integer to the console.