Get file time windows

GetFileTime function (fileapi.h)

Retrieves the date and time that a file or directory was created, last accessed, and last modified.

Syntax

Parameters

A handle to the file or directory for which dates and times are to be retrieved. The handle must have been created using the CreateFile function with the GENERIC_READ access right. For more information, see File Security and Access Rights.

A pointer to a FILETIME structure to receive the date and time the file or directory was created. This parameter can be NULL if the application does not require this information.

A pointer to a FILETIME structure to receive the date and time the file or directory was last accessed. The last access time includes the last time the file or directory was written to, read from, or, in the case of executable files, run. This parameter can be NULL if the application does not require this information.

A pointer to a FILETIME structure to receive the date and time the file or directory was last written to, truncated, or overwritten (for example, with WriteFile or SetEndOfFile). This date and time is not updated when file attributes or security descriptors are changed. This parameter can be NULL if the application does not require this information.

Return value

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Not all file systems can record creation and last access times and not all file systems record them in the same manner. For example, on FAT, create time has a resolution of 10 milliseconds, write time has a resolution of 2 seconds, and access time has a resolution of 1 day (really, the access date). Therefore, the GetFileTime function may not return the same file time information set using the SetFileTime function.

NTFS delays updates to the last access time for a file by up to one hour after the last access. NTFS also permits last access time updates to be disabled. Last access time is not updated on NTFS volumes by default.

Windows ServerВ 2003 and WindowsВ XP:В В Last access time is updated on NTFS volumes by default.

For more information, see File Times.

If you rename or delete a file, then restore it shortly thereafter, Windows searches the cache for file information to restore. Cached information includes its short/long name pair and creation time.

How to get date / time in batch file

This post explains how to get current date and time from command prompt or in a batch file.

How to get date and time in a batch file

Below is a sample batch script which gets current date and time
Datetime.cmd

When we run the above batch file

Get date from command line

To print today’s date on the command prompt, we can run date /t .

Just running date without any arguments prints the current date and then prompts to enter a new date if the user wants to reset it.

In addition to date command, we also have an environment variable using which we can find today’s date.

How to get only the date in MM/DD/YYYY format?

You may want to exclude the day (like ‘Sun’ in the above example) and print only the date in MM/DD/YYYY format. The below command works for the same.

Читайте также:  Как поставить драйвер нвидиа линукс

Get time from command prompt

Similar to date command, we have the command time which lets us find the current system time. Some examples below.

As you can see, the command prints the time in different formats. It prints in 12 hour format when /t is added and in 24 hours format without /t

We can also get the current time from environment variables.

Get date and time

Sir I want to get all outdated drivers in our pc through command prompt please help and
reply
Thanks

That last part is so helpful and outstanding! Thank you so much!! 😀
-Matthew

I want the last week date from the current date :-This is the script,I am using for the getting the current date.
for /F “tokens=2” %i in (‘date /t’) do echo %i
05/14/2015

these comments were helpful but how do you make a real time updating clock in 12 hour format in a batch file?

Create a file called realtimeClock.bat.
This is the contents of realtimeClock.bat:
——
@echo off
:getTime
echo The current time is %time%
cls
goto :getTime
——
Run, and enjoy.

Excellent guideline. If the hour (time) is less than 10 then %time% return a space before the hour, so I prefer to use the ‘time /t’ approach.

You can solve that by:
echo %TIME: =0%

(there’s a space between : and =). That will replace the space with a 0
Let’s say you wanted to use the variable to create a filename or log based on the current time:

rem Extract the hour and minute from the time
set TM=%TIME:

3,2%
rem Zero-pad the hour if it is before 10am
set TM=%TM: =0%
echo %TM%

output is:
0803
for 8:03am

I need to get the files based on current date. How ya the script look like. Can someone assist me

how to do this with date and time of a file ?
Why doesn’t it work with “ftime, fdate” ?

please any hint how to do this would be great !

Reply to markus’ question: How to do this with date and time of a file ?

To read the date+time of a file, call DIR in a FOR loop, like so:
FOR /F “tokens=1,2,3,4,*” %%a in (‘DIR “filename.ext”/4 ^| find “/”‘) do set “filedatetime=%%a %%b %%c” & set “filesize=%%d” & set “filename=%%e” & REM Do whatever you want here

Note: There is an apostrophe (single-quote) between the double-quote and the right-paren.

You can, of course, use any switches you want in the DIR command to refine your selection criteria. Type DIR /? for more info.

The FIND command filters the output of DIR to eliminate the header and footer. (DIR /B only lists the filenames, not the dates.)

“tokens=1,2,3,4,*” parses the output into separate variables. The asterisk at the end puts the entire filename (including spaces) into the fifth variable.

how to output date /T and time /T?
like sun 1/1/2017 3:52 PM

Hello, I would need a batch file, with does the Reset function in Date and Time/Change Date and Time/change calendar settings/Reset.

Is it possible to get the date and then use it as an input string in a for loop so that the day can increment

I need a .bat script to change the system date one day ahead, (change it to tomorrow’s date). That’s it.

hello
I need to run a file in a certain date without using wndows Task Scheduler.
how can I do that using batch file?
please help me.

hello
I need to run a file in a certain date without using windows Task Scheduler.
how can I do that using batch file?
please help me.
please answer me through my G-mail
thanks alot

Читайте также:  Relax and recovery linux

All of the above scripts which call both time and date (or %time% and %date%) suffer from one minor problem: time and date are called separately, so if the script runs just before midnight (a very narrow window, to be sure – at most a few milliseconds), the date could roll over between the two calls and your result would be 24 hours early (i.e. just after midnight on the date that the command started).

Here are 2 solutions:
1.
for /f “tokens=2 delims==” %%I in (‘wmic os get localdatetime /format:list’) do set datetime=%%I
set datetime=%datetime:

8,6%
wmic gets the date + time in an atomic operation, so no rollover is possible.
The second line formats datetime in the form I needed for what I used it for. You can modify this line to format however suits your needs.

2.
:timeloop
set mydate=%date%
set mytime=%time%
if mydate NEQ %date% goto :timeloop

If the date rolls over between the two calls to %date%, just go back and try again.

SetFileTime function (fileapi.h)

Sets the date and time that the specified file or directory was created, last accessed, or last modified.

Syntax

Parameters

A handle to the file or directory. The handle must have been created using the CreateFile function with the FILE_WRITE_ATTRIBUTES access right. For more information, see File Security and Access Rights.

A pointer to a FILETIME structure that contains the new creation date and time for the file or directory. If the application does not need to change this information, set this parameter either to NULL or to a pointer to a FILETIME structure that has both the dwLowDateTime and dwHighDateTime members set to 0.

A pointer to a FILETIME structure that contains the new last access date and time for the file or directory. The last access time includes the last time the file or directory was written to, read from, or (in the case of executable files) run. If the application does not need to change this information, set this parameter either to NULL or to a pointer to a FILETIME structure that has both the dwLowDateTime and dwHighDateTime members set to 0.

To prevent file operations using the given handle from modifying the last access time, call SetFileTime immediately after opening the file handle and pass a FILETIME structure that has both the dwLowDateTime and dwHighDateTime members set to 0xFFFFFFFF.

A pointer to a FILETIME structure that contains the new last modified date and time for the file or directory. If the application does not need to change this information, set this parameter either to NULL or to a pointer to a FILETIME structure that has both the dwLowDateTime and dwHighDateTime members set to 0.

To prevent file operations using the given handle from modifying the last access time, call SetFileTime immediately after opening the file handle and pass a FILETIME structure that has both the dwLowDateTime and dwHighDateTime members set to 0xFFFFFFFF.

Return value

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Not all file systems can record creation and last access times and not all file systems record them in the same manner. For example, on FAT, create time has a resolution of 10 milliseconds, write time has a resolution of 2 seconds, and access time has a resolution of 1 day (really, the access date). Therefore, the GetFileTime function may not return the same file time information set using SetFileTime. NTFS delays updates to the last access time for a file by up to one hour after the last access.

Читайте также:  Booting windows iso from grub

FILETIME structure (minwinbase.h)

Contains a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC).

Syntax

Members

The low-order part of the file time.

The high-order part of the file time.

Remarks

To convert a FILETIME structure into a time that is easy to display to a user, use the FileTimeToSystemTime function.

It is not recommended that you add and subtract values from the FILETIME structure to obtain relative times. Instead, you should copy the low- and high-order parts of the file time to a ULARGE_INTEGER structure, perform 64-bit arithmetic on the QuadPart member, and copy the LowPart and HighPart members into the FILETIME structure.

Do not cast a pointer to a FILETIME structure to either a ULARGE_INTEGER* or __int64* value because it can cause alignment faults on 64-bit Windows.

Not all file systems can record creation and last access time and not all file systems record them in the same manner. For example, on NT FAT, create time has a resolution of 10 milliseconds, write time has a resolution of 2 seconds, and access time has a resolution of 1 day (really, the access date). On NTFS, access time has a resolution of 1 hour. Therefore, the GetFileTime function may not return the same file time information set using the SetFileTime function. Furthermore, FAT records times on disk in local time. However, NTFS records times on disk in UTC. For more information, see File Times.

A function using the FILETIME structure can allow for values outside of zero or positive values typically specified by the dwLowDateTime and dwHighDateTime members. For example, the SetFileTime function uses 0xFFFFFFFF to specify that a file’s previous access time should be preserved. For more information, see the topic for the function you are calling.

GetFileTime

Функция GetFileTime извлекает дату и время файла, когда он был создан, когда к нему последний раз обращались, и когда он последний раз был изменен.

BOOL GetFileTime (

HANDLE hFile , // идентифицирует файл

LPFILETIME lpCreationTime , // адрес времени создания файла

LPFILETIME lpLastAccessTime , // адрес времени последнего доступа

LPFILETIME lpLastWriteTime // адрес времени последней записи в файл

Параметры

hFile — идентифицирует файл, для которого извлекаются дата и время. Файловый дескриптор должен быть создан с доступом GENERIC_READ к файлу.

lpCreationTime — указывает на структуру типа FILETIME , которая получает дату и время создания файла. Значение этого параметра может быть равно NULL, если приложению не требуется эта информация.

lpLastAccessTime — указывает на структуру типа FILETIME , которая получает дату и время последнего доступа к файлу. Время последнего доступа включает в себя время, когда в последний раз: в файл записывалась информация, читалась информация из файла, или, в случае исполняемых файлов, файл запускался на исполнение. Значение этого параметра может быть равно NULL, если приложению не требуется эта информация.

lpLastWriteTime — указывает на структуру типа FILETIME , которая получает дату и время последней записи в файл. Значение этого параметра может быть равно NULL, если приложению не требуется эта информация.

Возвращаемые значения

В случае успеха возвращается ненулевое значение.

В случае неудачи возвращается нуль. Для получения дополнительной информации об ошибке вызовите функцию GetLastError .

Комментарии

Файловые системы FAT и NTFS поддерживают время создания файла, время последнего доступа к файлу и время последней записи в файл.

Windows 95: Точность значения времени для файла в файловой системе FAT — 2 секунды. Точность значения времени для файлов в других файловых системах, например, на сетевых дисках, зависит от файловой системы, но также может быть ограничена удаленным устройством.

См. также

FILETIME, GetFileSize, GetFileType, SetFileTime .

Оцените статью