Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a Date object in Java stored as Java's Date type.

I also have a Gregorian Calendar created date. The gregorian calendar date has no parameters and therefore is an instance of today's date (and time?).

With the java date, I want to be able to get the year, month, day, hour, minute, and seconds from the java date type and compare the the gregoriancalendar date.

I saw that at the moment the Java date is stored as a long and the only methods available seem to just write the long as a formatted date string. Is there a way to access Year, month, day, etc?

I saw that the getYear(), getMonth(), etc. methods for Date class have been deprecated. I was wondering what's the best practice to use the Java Date instance I have with the GregorianCalendar date.

My end goal is to do a date calculation so that I can check that the Java date is within so many hours, minutes etc of today's date and time.

I'm still a newbie to Java and am getting a bit puzzled by this.

like image 401
daveb Avatar asked Oct 14 '22 22:10

daveb


People also ask

How does GregorianCalendar compare to date in Java?

equals() method compares this GregorianCalendar to the specified Object. The result is true if and only if the argument is a GregorianCalendar object that represents the same time value (millisecond offset from the Epoch) under the same Calendar parameters and Gregorian change date as this object.

How do you get month and year from a date Object in Java?

The getDayOfMonth() method returns the day represented by the given date, getMonth() method returns the month represented by the given date, and getYear() method returns the year represented by the given date.

What is the use of Calendar getInstance () in Java?

Calendar 's getInstance method returns a Calendar object whose calendar fields have been initialized with the current date and time: Calendar rightNow = Calendar.

How do I get the current year from a date in Java?

To get the previous year in Java, first we need to access the current year using the Year. now(). getValue() method and subtract it with -1 . Note: The getValue() method returns the current year in four-digit(2021) format according to the user's local time.


1 Answers

Use something like:

Date date; // your date
// Choose time zone in which you want to interpret your Date
Calendar 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.

like image 601
Florent Guillaume Avatar answered Oct 16 '22 12:10

Florent Guillaume