简体   繁体   中英

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.

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 . Hence, when you multiply the date * 1000 (both are int ), it returns 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

// 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. For easier maintenance, changing the type of NewFoodItem.date as long is the preferred one; much better if it's in millisecond also.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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