1,488
社区成员
发帖
与我相关
我的任务
分享
Option Explicit
'〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓
'GainFileTime 函数中的参数
' FileName ------------ String,文件的全路径。
' TimeItem ------------ Integer,指定函数要返回哪个项目的时间,具体值如下:
' 参数 TimeItem 传入值为 0 (默认值)时 GainFileTime 返回文件的创建时间;
' 参数 TimeItem 传入值为 1 时 GainFileTime 返回文件上一次访问的时间;
' 参数 TimeItem 传入值为 2 时 GainFileTime 返回文件上一次修改的时间。
' 返回值 -------------- Date,返回一个由 TimeItem 指定的项目时间。
'〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓
Private Type FILETIME
dwLowDateTime As Long
dwHighDateTime As Long
End Type
Private Type SYSTEMTIME
wYear As Integer
wMonth As Integer
wDayOfWeek As Integer
wDay As Integer
wHour As Integer
wMinute As Integer
wSecond As Integer
wMilliseconds As Integer
End Type
Private Const GENERIC_WRITE = &H40000000
Private Const OPEN_EXISTING = 3
Private Const FILE_SHARE_READ = &H1
Private Const FILE_SHARE_WRITE = &H2
'取得文件句柄需要用到的 API
Private Declare Function CreateFile Lib "kernel32" Alias "CreateFileA" (ByVal lpFileName As String, ByVal dwDesiredAccess As Long, ByVal dwShareMode As Long, ByVal lpSecurityAttributes As Long, ByVal dwCreationDisposition As Long, ByVal dwFlagsAndAttributes As Long, ByVal hTemplateFile As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
'GainFileTime 需要用到的 API
Private Declare Function GetFileTime Lib "kernel32" (ByVal hFile As Long, lpCreationTime As FILETIME, lpLastAccessTime As FILETIME, lpLastWriteTime As FILETIME) As Long
Private Declare Function FileTimeToSystemTime Lib "kernel32" (lpFileTime As FILETIME, lpSystemTime As SYSTEMTIME) As Long
Private Declare Function FileTimeToLocalFileTime Lib "kernel32" (lpFileTime As FILETIME, lpLocalFileTime As FILETIME) As Long
Public Function GainFileTime(ByVal FileName As String, Optional ByVal TimeItem As Integer = 0) As Date
Dim lngHandle As Long, I As Integer
Dim nFileTime(2) As FILETIME, lFileTime(2) As FILETIME
Dim SysTime As SYSTEMTIME
'验证文件是否存在,如果不存在则退出此函数
If Dir(FileName) = "" Then Exit Function
'打开文件获得文件句柄
lngHandle = CreateFile(FileName, GENERIC_WRITE, FILE_SHARE_READ Or FILE_SHARE_WRITE, ByVal 0&, OPEN_EXISTING, 0, 0)
'获取该文件的创建 / 访问 / 修改的日期 / 时间属性
GetFileTime lngHandle, nFileTime(0), nFileTime(1), nFileTime(2)
'关闭该句柄
CloseHandle lngHandle
'将文件时间转换为本地文件时间
For I = 0 To 2
FileTimeToLocalFileTime nFileTime(I), lFileTime(I)
Next
'将文件时间转换为系统文件时间
FileTimeToSystemTime lFileTime(TimeItem), SysTime
'将 SYSTEMTIME 类型中的各项元素组合起来赋值给函数
GainFileTime = CDate(SysTime.wYear & "-" & SysTime.wMonth & "-" & SysTime.wDay & " " _
& SysTime.wHour & ":" & SysTime.wMinute & ":" & SysTime.wSecond)
End Function
Option Explicit
Private Sub Command1_Click()
MsgBox GainFileTime("C:\1.txt", 2)
End Sub
MsgBox FileDateTime(FilePath) 'FilePath为文件路径