File Created Date Time in ColdFusion / CFML
By Pete Freitag
Today I needed to get the time that a file was created from within some CFML code. I had first thought that cfdirectory
or directoryList
would return this, but it only returns the date the a file was modified, not the date that it was created.
My next thought was that getFileInfo
must return this, but again it only returns the date that the file was last modified. Even java.io.File
only returns the last modified date, not the date the file was created.
The Solution
The solution is to use Java's NIO (Native IO) file API, and more specifically the java.nio.file.attribute.BasicFileAttributes
implementation.
Here's a function that will return the date that a file was created, modified, and the date that the file was last accessed.
function getFileAttributes(path) { var filePath = createObject("java", "java.nio.file.Paths").get(arguments.path, []); var basicAttribs = createObject("java", "java.nio.file.attribute.BasicFileAttributes"); var fileAttribs = createObject("java", "java.nio.file.Files").readAttributes(filePath, basicAttribs.getClass(), []); return { "creationTime": fileAttribs.creationTime().toString(), "lastModifiedTime": fileAttribs.lastModifiedTime().toString(), "lastAccessTime": fileAttribs.lastAccessTime().toString() }; }
Note that some linux file system implementations don't actually keep track of the last access time (or atime as they call it), so you might get the last modified date there instead.
File Created Date Time in ColdFusion / CFML was first published on March 09, 2023.
If you like reading about java, or cfml then you might also like:
- URL Safe Base64 Encoding / Decoding in CFML
- ColdFusion Heap / Non-Heap Memory Usage Script
- CFML on Google App Engine for Java
- Serializing CFC's in ColdFusion 8
The FuseGuard Web Application Firewall for ColdFusion & CFML is a high performance, customizable engine that blocks various attacks against your ColdFusion applications.
One suggestion: I think some may misinterpret the post by the title alone ,"File Create Time". I thought it was going to be about "how long it took" to create a file. If you may be open to a tweak, I think if it said "File Creation DateTime" that could avoid that confusion. But of course anyone who reads the post will realize what you were getting at.
Oh, and if you may consider that, note also a minor typo in the text: "returns the date the a file". And while I suppose you may have meant to say, "returns the date that a file", since the tag/function can indeed return a datetime, perhaps it could be "returns the datetime that a file".
As always, just trying to help.