简体   繁体   English

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

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

EDIT: Removed the '*1000' and still getting incorrect date but updated the log below to show what I am now getting. 编辑:删除了'* 1000'并仍然得到不正确的日期,但更新了下面的日志以显示我现在得到的内容。

Below is my code snippet and my log and I thought I implemented it correctly so I don't know why it isn't giving me the correct conversion: 以下是我的代码段和日志,我以为我正确实现了它,所以我不知道为什么它没有给我正确的转换:

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);

It won't let me post an image but the log looks like this: 它不会让我发布图像,但日志如下所示:

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

I just tested with some assumption, and it seems that the problem is related to integer overflow . 我只是用一些假设进行了测试,看来问题与整数溢出有关

I assume you defined NewFoodItem.date as int , instead of long . 我假设您将NewFoodItem.date定义为int ,而不是long Hence, when you multiply the date * 1000 (both are int ), it returns int . 因此,当您将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

When I try changing one of them to long , it behaves as expected 当我尝试将其中之一更改为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

Generally when working with Date in Java, we define them as long since normally they are in millisecond. 通常,在Java中使用Date时,我们将它们定义的long因为通常它们以毫秒为单位。 For easier maintenance, changing the type of NewFoodItem.date as long is the preferred one; 为了易于维护,改变的类型NewFoodItem.date作为long是首选的一个; much better if it's in millisecond also. 如果也是毫秒也更好。

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

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