daveb daveb - 16 days ago 5
Java Question

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 in java stored as Java Date type.

I also have a gregorian calender created date. The gregorian calendar date has no parameters and therefore is an instance of todays 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 type have been deprecated. I was wondering how best 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 todays date and time.

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

Answer

Use something like:

    Date date; // your date
    Calendar cal = Calendar.getInstance();
    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.

Comments