Jayyrus
Jayyrus

Reputation: 13061

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?

Upvotes: 1

Views: 213

Answers (3)

Óscar López
Óscar López

Reputation: 236140

If you need to obtain a new Date object from a GregorianCalendar, do this:

Date d = g.getTime();

In this way, you won't have to use deprecated methods, and the result will be the one you expect. Also, if you need to obtain the current date, simply write new Date(), no need for a GregorianCalendar.

As far as date comparisons go, you can use Date's compareTo(), after() and before() methods. Again, there's no need for a GregorianCalendar.

Upvotes: 1

Renato
Renato

Reputation: 13710

Create a Calendar, then set the time using the Date object, then you can get any information you need from it.

Example:

Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
int day = cal.get(Calendar.DAY_OF_MONTH);
// and so on....

Upvotes: 0

aioobe
aioobe

Reputation: 421280

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)

Upvotes: 2

Related Questions