Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Date getTime function returns negative value

Tags:

java

date

I'm converting a String to a date, then converting it integer value to make the comparison between dates easier. Here's my code:

SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz",Locale.US);
lastModified = "Sun, 02 Oct 2011 18:38:26 GMT";
Date date = format.parse(lastModified);
lastModifiedDate = (int) date.getTime();

Then, I printer lastModifiedDate and it was (-974253872), I know it should be the time in milliseconds from Jan 1, 1970, but it's negative value, so what's happening?

Thanks for your help.

like image 439
Muayad Salah Avatar asked Feb 17 '15 10:02

Muayad Salah


1 Answers

date.getTime() returns a long. If you cast it to int, it may become negative due to overflow.

If you change your code to :

long lastModifiedDate =  date.getTime();

You'll get a positive value - 1317580706000 - which can't fit in an int variable.

like image 193
Eran Avatar answered Oct 25 '22 02:10

Eran