file.lastModified() is never what was set with file.setLastModified()

Harald Wilhelm picture Harald Wilhelm · Jul 9, 2011 · Viewed 13.6k times · Source

I do have a problem with millis set and read on Android 2.3.4 on a Nexus One. This is the code:

File fileFolder = new File(Environment.getExternalStorageDirectory(), appName + "/"
    + URLDecoder.decode(folder.getUrl()));
if (fileFolder != null && !fileFolder.exists()) {
  fileFolder.setLastModified(1310198774);
  fileFolder.mkdirs();
  fileFolder.setLastModified(1310198774);
}

if (fileFolder != null && fileFolder.exists()) {
  long l = fileFolder.lastModified();
}

In this small test I write 1310198774 but the result that is returned from lastModified() is 1310199771000.

Even if I cut the trailing "000" there's a difference of several minutes.

I need to sync files between a webservice and the Android device. The lastmodification millis are part of the data sent by this service. I do set the millis to the created/copied files and folders to check if the file/folder needs to be overwritten.

Everything is working BUT the millis that are returned from the filesystem are different from the values that were set.

I'm pretty sure there's something wrong with my code - but I can't find it.

Many thanks in advance. HJW

Answer

Gray picture Gray · Aug 31, 2011

So maybe I'm missing something but I see some problems with your code above. Your specific problem may be due (as @JB mentioned) to Android issues but for posterity, I thought I'd provide an answer.

First off, File.setLastModified() takes the time in milliseconds. Here are the javadocs. You seem to be trying to set it in seconds. So your code should be something like:

fileFolder.setLastModified(1310198774000L);

As mentioned in the javadocs, many filesystems only support seconds granularity for last-modification time. So if you need to see the same modification time in a file then you should do something like the following:

private void changeModificationFile(File file, long time) {
    // round the value down to the nearest second
    file.setLastModified((time / 1000) * 1000);
}