I want to get Year, Month, Day, etc from Java Date to compare with Gregorian Calendar date in Java. Is this possible? I want to get Year, Month, Day, etc from Java Date to compare with Gregorian Calendar date in Java. Is this possible? java java

I want to get Year, Month, Day, etc from Java Date to compare with Gregorian Calendar date in Java. Is this possible?


Use something like:

Date date; // your date// Choose time zone in which you want to interpret your DateCalendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Paris"));cal.setTime(date);int year = cal.get(Calendar.YEAR);int month = cal.get(Calendar.MONTH);int day = cal.get(Calendar.DAY_OF_MONTH);// etc.

Beware, months start at 0, not 1.

Edit: Since Java 8 it's better to use java.time.LocalDate rather than java.util.Calendar. See this answer for how to do it.


With Java 8 and later, you can convert the Date object to a LocalDate object and then easily get the year, month and day.

Date date = new Date();LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();int year  = localDate.getYear();int month = localDate.getMonthValue();int day   = localDate.getDayOfMonth();

Note that getMonthValue() returns an int value from 1 to 12.


You could do something like this, it will explain how the Date class works.

String currentDateString = "02/27/2012 17:00:00";SimpleDateFormat sd = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");Date currentDate = sd.parse(currentDateString);String yourDateString = "02/28/2012 15:00:00";SimpleDateFormat yourDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");Date yourDate = yourDateFormat.parse(yourDateString);if (yourDate.after(currentDate)) {    System.out.println("After");} else if(yourDate.equals(currentDate)) {    System.out.println("Same");} else {    System.out.println("Before");}