Converting date to milliseconds, wrong result

I want to convert two dates to milliseconds, but the given result is not correct, is there something wrong with the code? How to solve it differently ...

GregorianCalendar c1 = new GregorianCalendar();
GregorianCalendar c2 = new GregorianCalendar();

c1.set(2013, 01, 31, 16, 44, 49);
c2.set(2013, 02, 01, 12, 59, 55);

System.out.println("c1 = "+c1.getTimeInMillis()+"\nc2 = "+ c2.getTimeInMillis());

output:
c1 = 1362300289619
c2 = 1362113995619

      

After calculating the time, this gives the following result: 0Month -2Day -3Hour -44Min -54Sec

what is wrong. And there should be something like this: 0Month 0Day 20Hour 15Min 6Sec

.

c1 is greater than c2 because it gives the wrong result, but why did it happen that c1 becomes larger than c2, then it is impossible to calculate the time between two dates. if anyone knows please help me, thanks in advance.

+3


source to share


4 answers


The months are 0-based, so in your example, c1 is February 31, which is interpreted as March 3 (only 28 days in February), and c2 is March 1.



+8


source


This code:

c1.set(2013, 01, 31, 16, 44, 49);

      

trying to set on Feb 31, because Java months are 0. I suspect you end up on Mar 3, 3 days after Feb 28. This is clearly after March 1, which is set in your c2

.

From the docs Calendar.set

:



month is the value used to set the MONTH calendar field. The month value is 0. for example, 0 for January.

Whenever you find that your code is behaving strangely, always check the details of any API call you are not sure about.

Alternatively, I highly recommend you use Joda Time if at all possible - it is a much more convenient API.

+5


source


Thanks guys for your answer! Problem solved now, only subtract 1 from months before I don't know that in Java months start from scratch ... here's how to solve

c1.set (2013, (01-1), 31, 16, 44, 49);
   c2.set (2013, (02-1), 01, 12, 59, 55);

Instead, you can use constants in the class java.util.Calendar

to make your code easier to read.

c1.set(2013, Calendar.JANUARY, 31, 16, 44, 49);
c2.set(2013, Calendar.FEBRUARY, 01, 12, 59, 55);

      

+1


source


Thanks guys for your answer! The problem is solved now by only subtracting 1 from months before I don't know that in Java months starts at zero ... this is how to solve:

c1.set(2013, (01-1), 31, 16, 44, 49);
c2.set(2013, (02-1), 01, 12, 59, 55);

      

0


source







All Articles