2

I am writing a program which chooses images based on specific times. I store the name of each image within a directory aswell as its last modified time as to reference each image. However when storing the date of the last modified for each image, it seems to be hour hour behind for some reason. Which means the images one hour later are being chosen instead.

System.out.println(listOfFiles[i].getName());

originalImageNames.add(listOfFiles[i].getAbsolutePath());

date = listOfFiles[i].lastModified();
Date fDate = new Date(date);

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm");
String dateString = sdf.format(fDate);
System.out.println(dateString);

originalImageDates.add(dateString);

The Correct image name is being printed but the last modified time of this image is 10:29. However the image date printed and stored is 09:29.

5
  • 2
    Are you on summer time? The time is being taken from the system, so it should'nt happen unless your clock is delayed Jun 12, 2012 at 1:49
  • Yes my system is adjusted for Daylight Saving Time. Jun 12, 2012 at 2:00
  • I just checked by choosing an image specifically and parsing its last modified time as shown below and it still results in a time an hour before the actual last modified when checked through explorer. I have no idea why. Is there any way I could add an hour onto the parsed time? Jun 12, 2012 at 2:21
  • try this format and see if the tz matches your expectations: "dd-MM-yyyy HH:mm, zzzz"
    – akf
    Jun 12, 2012 at 2:51
  • Looks like windows and java have different rules for daylight savings time in your jurisdiction. Is one of them possibly out of date?
    – Affe
    Jun 12, 2012 at 3:15

2 Answers 2

1

File.lastModified() operates in msecs measured from the epoch (00:00:00 GMT, January 1, 1970). Note the GMT-timezone. SimpleDateFormat compensates for your local time zone; so if you're one hour off GMT that could explain it.

http://docs.oracle.com/javase/7/docs/api/java/io/File.html#lastModified() http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html#format(java.util.Date, java.lang.StringBuffer, java.text.FieldPosition)

-2

I still have no idea over the cause, but I managed to fix my program by manually adding one hour onto all the times. This isn't how I wanted to fix this problem, but at this point in time it will do!

The Code that fixed the problem is shown below

    Calendar gc = new GregorianCalendar();
    gc.setTime(fDate);
    gc.add(Calendar.HOUR, 1);
    java.util.Date d2 =  gc.getTime();

Thanks :)

1
  • This should never have been done, because when the clocks change again you code will be an hour ahead, and so broken again.
    – Alan
    Apr 16, 2013 at 12:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.