Search code examples
javadategregorian-calendar

Ambiguous result date java


i'm retrieving a strange result:

First i get current date using GregorianCalendar:

GregorianCalendar g = new GregorianCalendar();
int m = g.get(Calendar.DAY_OF_MONTH);
int d = g.get(Calendar.DAY_OF_WEEK);
int y = g.get(Calendar.YEAR);

Then i create new object Date:

Date d = new Date(d,m,y);

Then i print them together in this way:

System.out.println(d+" - "+m+" - "+y+" - "+d);

and i get:

1 - 18 - 2012 - Thu Jan 02 00:00:00 CET 1908

can you explain me why? is for deprecated method Date(day,mouth,year) ? if yes, how can i compare two Date using that parameters?


Solution

  • Then i create new object Date:

    Date d = new Date(d,m,y);
    

    The order of the arguments to the constructor is year, month, date, nothing else.

    From the documentation:

    Date(int year, int month, int day)


    how can i compare two Date using that parameters?

    Depends on how you want to compare two Dates. If you just want to figure out which comes first, you could use Date.before and Date.after.

    But as you've noted, the Date class is deprecated. Use the Calendar class instead, (or better yet, the Joda Time library)