繁体   English   中英

使用Java将Unix时代转换为人类可读的日期不正确

[英]Incorrect date when converting unix epoch to human readable using Java

编辑:删除了'* 1000'并仍然得到不正确的日期,但更新了下面的日志以显示我现在得到的内容。

以下是我的代码段和日志,我以为我正确实现了它,所以我不知道为什么它没有给我正确的转换:

NewFoodItem foodItem = data.get(position);
String date = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new java.util.Date (foodItem.date));
String a =  Integer.toString(foodItem.date);
Log.d("returnedDate:", a);
Log.d("formattedDate:", date);

它不会让我发布图像,但日志如下所示:

D/returnedDate:  1409012824
D/formattedDate: 01/17/1970 02:23:32
D/returnedDate:  1409013004
D/formattedDate: 01/17/1970 02:23:33

我只是用一些假设进行了测试,看来问题与整数溢出有关

我假设您将NewFoodItem.date定义为int ,而不是long 因此,当您将date * 1000 (都为int )相乘时,它将返回int

int d = 1409012824; // foodItem.date
int d1000 = d * 1000; // returns 263550912 because of overflow, instead of 1409012824000

String date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
    .format(new Date(d1000)); // returns 01/04/1970 08:42:30

当我尝试将其中之一更改为long ,它的行为符合预期

// case 1
long d = 1409012824;
long d1000 = d * 1000; // now returns 1409012824000 correctly

String date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
    .format(new Date(d1000)); // returns 08/26/2014 08:27:04

// case 2
int d = 1409012824;
long d1000 = d * 1000L; // note the "L" suffix to indicate the number as long 
long d1000f = d * 1000; // FAIL, still returns 263550912 because of integer overflow

String date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
    .format(new Date(d1000)); // returns 08/26/2014 08:27:04
String date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
    .format(new Date(d1000f)); // returns 01/04/1970 08:42:30

通常,在Java中使用Date时,我们将它们定义的long因为通常它们以毫秒为单位。 为了易于维护,改变的类型NewFoodItem.date作为long是首选的一个; 如果也是毫秒也更好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM