Java Date getTime函数返回负值 [英] Java Date getTime function returns negative value

查看:2564
本文介绍了Java Date getTime函数返回负值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将一个字符串转换为一个日期,然后转换它的整数值,使日期之间的比较更容易。这是我的代码:

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

然后,我打印机lastModifiedDate是(-974253872),我知道应该是1970年1月1日以来的毫秒数,但它是负值,所以发生了什么?



感谢您的帮助。

解决方案

date.getTime()返回一个 long 。如果您将其转换为 int ,则可能会由于溢出而变为否定。



如果将代码更改为:

  long lastModifiedDate = date.getTime(); 

您将获得一个正值 - 1317580706000 - 这不能适用于int变量。 / p>

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.

解决方案

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.

这篇关于Java Date getTime函数返回负值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆