Vipul
Vipul

Reputation: 836

Compare Calendar and java.util.date dates

Hi i am creating instance of Calendar Using:

Calendar calendarDate=Calendar.getInstance();
            calendarDate.set(2012, 6, 1,0,0,0);
                Date date1=calendar.getTime();

After that i create instance of java.util.date using:

Date date2=new Date(2012 - 1900,7-1, 01);

Now when i am trying to compare dates using following code:

System.out.println(date2.compareTo(date1));
System.out.println(date1.compareTo(date2));

it prints -1 and 1 instead of 0(zero).
Can any one help me to find what's goes wrong ?

Upvotes: 2

Views: 15076

Answers (5)

Peter Lawrey
Peter Lawrey

Reputation: 533870

Dates are GMT except when using the deprecated constructors. There will be a difference here because you also need to set the milli-seconds to 0 as well.

Calendar calendarDate=Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendarDate.set(2012, Calendar.JULY, 1,0,0,0);
calendarDate.set(Calendar.MILLISECOND, 0);
Date date1 = calendarDate.getTime();
Date date2=new Date(2012 - 1900,7-1, 1, 1, 0, 0);
System.out.println(date1);
System.out.println(date2);
System.out.println(date2.compareTo(date1));
System.out.println(date1.compareTo(date2));

prints

Sun Jul 01 01:00:00 BST 2012
Sun Jul 01 01:00:00 BST 2012
0
0

Note: Calendar will leave any field you don't set so the first set() will leave the milliseconds untouched.

Upvotes: 0

Francisco Spaeth
Francisco Spaeth

Reputation: 23913

Try to clear the value of calendar before set a new one. This will solve your problem.

Calendar calendarDate=Calendar.getInstance();
calendarDate.clear();
calendarDate.set(2012, 6, 1,0,0,0);

Test for it:

import java.util.Calendar;
import java.util.Date;

import org.junit.Assert;

public class DateTest {

    @org.junit.Test
    public void test() {
        Calendar calendarDate=Calendar.getInstance();
        calendarDate.clear();
        calendarDate.set(2012, 6, 1,0,0,0);
        Assert.assertEquals(0, calendarDate.getTime().compareTo(new Date(2012 - 1900,7-1, 01)));
    }

}

Upvotes: 5

Rajath
Rajath

Reputation: 21

Date and Calender classes are different. Most of the methods of java.util.Date are deprecated. Hence its better to use Calender class. For more info on methods check out the below url. http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html

Upvotes: 2

srini.venigalla
srini.venigalla

Reputation: 5145

where is date1 created? You seem to assume Calendar and Date are related. They are not.

Upvotes: 0

nate_weldon
nate_weldon

Reputation: 2349

http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Date.html#compareTo(java.lang.Object)

compareTo

Returns: the value 0 if the argument is a Date equal to this Date; a value less than 0 if the argument is a Date after this Date; and a value greater than 0 if the argument is a Date before this Date.

Upvotes: 1

Related Questions