2

I've a problem creating new date in Java. I receive from webservice a timestamp (for example 1397692800). You can see from this online converter that is equal to 17 Apr 2014. When I try to create a new date with this timestamp in Java

Date date = new Date (1397692800);

console says to me that is equal to Sat Jan 17 05:14:52 CET 1970. What's wrong with my code?

Charlotte
  • 135
  • 2
  • 10

2 Answers2

6

The Date(long) constructor takes the number of milliseconds since the Unix epoch. I strongly suspect that you've been given the number of seconds since the Unix epoch - so just multiply that value by 1000L.

Date date = new Date(timestamp * 1000L);

Make sure you use 1000L rather than 1000, as otherwise if timestamp is an int, it will perform the arithmetic in 32 bits instead of 64, and you're very likely to get the wrong results.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

java.time

The modern approach uses java.time classes.

Instant instant = Instant.ofEpochSecond( 1_397_692_800L ) ;

instant.toString(): 2014-04-17T00:00:00Z


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154