Finbarr
Finbarr

Reputation: 32186

SimpleDateFormat format wrong values

The following code:

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd");
System.out.println(sdf.format(new Date(1293253200))); // 12/25/2010 05:00 GMT
System.out.println(sdf.format(new Date(1293339600))); // 12/26/2010 05:00 GMT
System.out.println(sdf.format(new Date(1293426000))); // 12/27/2010 05:00 GMT

prints:

01/16
01/16
01/16

Using a default DateFormat via SimpleDateFormat.getDateInstance(); prints these dates as 16-Jan-1970. What is going on?

Upvotes: 2

Views: 2204

Answers (4)

mtk
mtk

Reputation: 13717

As pointed by mhaller, you have indeed mistaken the milli-seconds and seconds in this case.

The overloaded constuctor of Date takes its parameter as long. The following snippet from the java-doc page.

Parameters:

date - milliseconds since January 1, 1970, 00:00:00 GMT not to exceed the milliseconds representation for the year 8099. A negative number indicates the number of milliseconds before January 1, 1970, 00:00:00 GMT.

Upvotes: 0

Ken Bloom
Ken Bloom

Reputation: 58800

The Date constructor expects a number of milliseconds since the epoch, but the number you're passing is in seconds since the epoch. Multiply it by 1,000 and you'll get the right date.

Upvotes: 2

mhaller
mhaller

Reputation: 14222

You are mixing milliseconds and seconds. 1293253200 is indeed 16. January 2010. You have to multiply with 1000 to get the dates you wanted:

Date date = new Date(1293253200L*1000L);
Sat Dec 25 06:00:00 CET 2010

Upvotes: 8

Nikita Rybak
Nikita Rybak

Reputation: 68026

Please check documentation of Date(long) constructor: it takes values in milliseconds, not seconds.
new Date(1293253200000l) should do just fine.

PS. Many IDE's provide inline documentation, so you don't even have to open the browser.

Upvotes: 4

Related Questions