Java 7 NIO.2 Files.getLastModifiedTime time zone
Asked Answered
T

2

8

I'm writing a program which needs to determine files/directories last modified time. I want to handle this time using Joda Time, and I'm using Java 7 NIO.2 class Files to get file last modified time. Its getLastModifiedTime() method returns an instance of FileTime class, which has convenient method toMillis(), whose result I pass to Joda Time DateTime class constructor:

new DateTime(Files.getLastModifiedTime(path).toMillis());

However, I have a feeling that I'm doing this wrong, since DateTime(long) constructor explicitly mentions that DateTime instance will be created with default time zone. FileTime docs, however, do not mention its time zone anywhere. I looked through FileTime code; it seems to be very simple, and its toString() method suggests that it is using UTC time zone (it creates a Calendar in UTC time zone and sets its milliseconds directly).

So, does FileTime uses UTC or local time? What is the correct way to convert FileTime to DateTime?

Tena answered 26/8, 2013 at 6:23 Comment(0)
H
6

A Java millisecond timestamp is a UTC timestamp. It's what FileTime.toMillis() returns, and what the DateTime constructor expects. The same applies to other Java API methods; e.g. the System.currentTimeMillis() method, the java.util.Date constructor, and so on.

They all work the same way. And, indeed, so do other Unix / Linux / OSX library methods in other programming languages.

The only case where this breaks is if someone configures / sets the system clock incorrectly.

Headreach answered 26/8, 2013 at 6:51 Comment(1)
Thank you, now I understand. For some reason I thought that DateTime constructor expected timestamp in local time zone, but, as you said, timestamp is always in UTC. Then DateTimeZone argument in another DateTime constructor just defines how this timestamp should be viewed.Tena
C
1

FileTime.toMillis() API says it returns the value in milliseconds, since the epoch (1970-01-01T00:00:00Z). new DateTime(millis) creates a DateTime instance wich holds time in milliseconds from the Java epoch of 1970-01-01T00:00:00Z and Chronology in the default time zone which determines how the millisecond value is converted into the date time fields.

Circulate answered 26/8, 2013 at 6:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.