Bargitta
Bargitta

Reputation: 2406

why java.sql.Timestamp return negative value when the date is after 1970-01-01

Timestamp timestamp = Timestamp.valueOf("1970-01-01 01:00:00");
System.out.println(timestamp.getTime());

Any idea this code returns -25200000 ? I thought time after 1970-01-01 00:00:00 will be positive.

Upvotes: 0

Views: 631

Answers (1)

Basil Bourque
Basil Bourque

Reputation: 338181

You are using a terrible date-time class that was supplanted years ago by the modern java.time classes defined in JSR 310. Never use java.sql.Timestamp.

Parse your input as a LocalDateTime because it lacks an indicator of time zone or offset-from-UTC. Replace the SPACE in middle with a T to comply with ISO 8601 standard for date-time formats.

String input = "1970-01-01 01:00:00".replace( " " , "T" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;

Apparently you mean for that to represent a moment in UTC. Apply an offset to get an OffsetDateTime.

OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ) ;

Get a count of milliseconds since the epoch reference of first moment of 1970 in UTC.

long millis = odt.toInstant().toEpochMilli() ;

3600000

Upvotes: 1

Related Questions