- Как можно работать с переменными среды %date% и %time% в коммандных файлах Windows .cmd / .bat
- How to get date / time in batch file
- How to get date and time in a batch file
- Get date from command line
- How to get only the date in MM/DD/YYYY format?
- Get time from command prompt
- Get date and time
- Configure Date, Time and Time Zone settings in Windows Server 2016
- Set time, date, and time zone settings from the graphical interface
- Set time, date, and time zone settings on command prompt
- Set time, date and time zone settings on Powershell
Как можно работать с переменными среды %date% и %time% в коммандных файлах Windows .cmd / .bat
Иногда требуется сформировать переменную даты и времени в cmd / bat скриптах windows так, как нужно нам, а не так, как нам отдаёт операционная система.
Например чтоб добавить эти данные в log файл, для фиксации времени или даты события, создать файл с именем, в котором должны фигурировать данные даты или времени (день, месяц, год, час, минуты, скунды, миллисекунды.) Да мало-ли, какие у нас задачи. Подключаем нашу фантазию 🙂
В следующем примере мы видим разбиение переменных по нужным нам шаблонам.
h- час 2 знака (то есть час будет выдаваться в следующем виде — 01, 02, . 09, . , 12, . 24)
m — минуты 2 знака
s — секунжы 2 знака
ms — миллисекунды 2 знака, почему-то от 0 до 99
dd — день 2 знака
mm — месяц 2 знака
yyyy — год 4 знака
Пример использования переменных %DATE% и %TIME% в скриптах cmd / bat Windows:
@echo off
set h=%TIME:
9,2%
set curtime=%h%:%m%:%s%:%ms%
set dd=%DATE:
3,2%
set yyyy=%DATE:
6,4%
set curdate=%dd%-%mm%-%yyyy%
set curdatetime=%curdate% %curtime%
echo Текущее время — %curdatetime%
В некоторых версиях Windows формат выдачи даты и времени другой, поэтому данный скрипт может работать совсем так как нам нужно.
По идее, подобным способом можно брать части любых переменных, суть в том что формат здесь такой:
Первая цифра после :
— это номер символа, с которого мы начинаем брать значение, вторая цифра это сколько символов захватывать.
Таким образом получается что мы можем взять для своих нужд любую часть, любой доступной нам переменной среды Windows.
Мне известны следующие переменные, значения которых мы можем получить:
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
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.
Configure Date, Time and Time Zone settings in Windows Server 2016
The correct date, time, and time zone are one of the first settings a Windows Server should have. In today’s article, we’ll see how we can change time, date, and time zone through the graphical environment, command line and Powershell.
Set time, date, and time zone settings from the graphical interface
The process is very simple. Right-click the time field in the lower right corner and then click the Adjust date/time option.
In the settings window, you can change the time, date, and time zones of each Windows Server. I do not think there is a need for further guidance as it is a simple process.
Alternatively, you can open the time and date settings window by clicking on the corresponding field in the Local Server section of the Server Manager.
As you will see, in this case, opens the “old” management window through which you can set the time, date and time zone.
Set time, date, and time zone settings on command prompt
By typing the following command will open the time and date setting window, even in a Server Core installation.
To display the current date and time, enter the following commands.
To set time and date, you can use the corresponding Time and Date commands at the command line.
In Windows Server 2012 have been added the Timezone Utility (tzutil) tool that allows us to display and set a time zone through the Windows command line.
First, open the command line with administrator privileges and make sure you are in the System32 folder.
To display the current Windows Server Time Zone, type the following command.
To display all available time zones, type the following command.
To change the current time zone in Windows Server, type the following command, between the doubles, enter the time zone as it appears in the list of the previous command. For example, for the Greek time zone type:
tzutil /s «GTB Standard Time»
To confirm that the time zone has changed, you can see the corresponding registry entry by using the following command from within the same command-line window.
reg query HKLM\SYSTEM\CurrentControlSet\Control\TimeZoneInformation
Set time, date and time zone settings on Powershell
To view the current date and time, type the following command.
To set the time and date through Powershell the process is very easy. Use the following command as an example by changing the date and time values.
Set-Date -Date «06/06/2017 14:45»
Alternatively, you can simply type the Set-Date command and promptly you will be prompted to enter the server’s date and time.
To view the current time zone through Powershell, type the following command.
Before changing the time zone, you will need to know the right name. Type the following command to see all available time zones in Windows Server.
To change the time zone, use the following command along with the corresponding time zone of your server.