0

The code is below:

DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); String logTime = format.format(new Date((format.parse("2013-6-30").getTime()+25*24*3600*1000))); String logTime1 = format.format(new Date((format.parse("2013-6-30").getTime()+24*24*3600*1000))); System.out.println("logTime: "+logTime); System.out.println("logTime1: "+logTime1); 

This is the output:

 logTime: 2013-06-05 logTime1: 2013-07-24 

What is wrong here?

3
  • I am not sure, what the question ist, but in the first case you multiply by 25, the second time by 24. Why is that? Commented Aug 1, 2013 at 5:54
  • I assume he means that adding 24 days is not a problem but adding 25 days is. Commented Aug 1, 2013 at 6:00
  • the time by 24 is normal,but when multiply 25,it becomes the wrong date. Commented Aug 1, 2013 at 6:02

1 Answer 1

5

You have an overflow. Try

25L * 24*3600*1000 

so the value is a long. Your IDE should highlight that what you have will overflow.

enter image description here

this prints a number which is clearly incorrect.

-2134967296 

DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); long time = format.parse("2013-6-30").getTime(); String logTime = format.format(new Date(time + 25L * 24 * 3600 * 1000)); String logTime1 = format.format(new Date(time + 24L * 24 * 3600 * 1000)); System.out.println("time + 25d: " + logTime); System.out.println("time + 24d: " + logTime1); 

prints

time + 25d: 2013-07-25 time + 24d: 2013-07-24 
Sign up to request clarification or add additional context in comments.

5 Comments

Didn't know you worked for jetbrains! ;-) (ps: netbeans does not give any warnings... pfff)
I use Ecipse,because it's the because IDE of java I think
Eclipse should compile the code the same as you would get on the command line. Eclipse may have less warnings, but I don't believe it is the cause of the problem.
Actually it is the right the result, just not the one you expect.
An int is a 32-bit signed value, if you perform a calculation which is too large for it, only the lower 32-bits are preserved. This is defined in the JLS as it is how most CPUs behave. It is how 32=bit int behave in C.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.