- Как можно работать с переменными среды %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
- Дата date
- Синтаксис Syntax
- Параметры Parameters
- Примеры Examples
- Изменение формата отображения даты
- Format Windows command line date
- 8 Replies to “Format Windows command line date”
Как можно работать с переменными среды %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.
Дата date
Отображает или задает системную дату. Displays or sets the system date. Если используется без параметров, Дата отображает текущий параметр системной даты и предлагает ввести новую дату. If used without parameters, date displays the current system date setting and prompts you to enter a new date.
Чтобы использовать эту команду, необходимо быть администратором. You must be an administrator to use this command.
Синтаксис Syntax
Параметры Parameters
Параметр Parameter | Описание Description |
---|---|
Устанавливает указанную дату, где Month — месяц (одна или две цифры, включая значения от 1 до 12), день — день (одна или две цифры, включая значения от 1 до 31), а year — год (две или четыре цифры, включая значения от 00 до 99 или от 1980 до 2099). Sets the date specified, where month is the month (one or two digits, including values 1 through 12), day is the day (one or two digits, including values 1 through 31), and year is the year (two or four digits, including the values 00 through 99 or 1980 through 2099). Необходимо разделить значения для месяца, дня и года с точками (.), дефисами (-) или знаками косой черты (/). You must separate values for month, day, and year with periods (.), hyphens (-), or slash marks (/). |
Примечание. Имейте в виду, что если для представления года используется 2 цифры, то значения 80-99 соответствуют 1980 – 1999. Note: Be aware that if you use 2 digits to represent the year, the values 80-99 correspond to 1980 through 1999.
Примеры Examples
Если расширения команд включены, для вывода текущей системной даты введите: If command extensions are enabled, to display the current system date, type:
Чтобы изменить текущую системную дату на 3 августа 2007, можно ввести любой из следующих элементов: To change the current system date to August 3, 2007, you can type any of the following:
Чтобы отобразить текущую системную дату, после чего появится запрос на ввод новой даты, введите: To display the current system date, followed by a prompt to enter a new date, type:
Для сохранения текущей даты и возврата в командную строку нажмите клавишу Ввод. To keep the current date and return to the command prompt, press ENTER. Чтобы изменить текущую дату, введите новую дату и нажмите клавишу Ввод. To change the current date, type the new date and then press ENTER.
Изменение формата отображения даты
Столкнулся с неприятной особенностью — на русской версии Windows 7 — Дата по умолчанию подается в Формате дд.MM.гггг
а в английской версии винды dd/MM/YYYY — работая с разными версиями нашел один одинаковый формат для обоих
yyyy-MM-dd — не могу сообразить как в коде поменять формат текущей даты на формат удобный мне. Команда DATE не имеет синтаксиса по изменению формата отображения. вручную средствами винды — всё получается захожу в консоль и там выбираю нужный формат — который вступает в силу после нажатия — ПРИМЕНИТЬ. Как в команднойстроке скрипт сделать что-б переводил дату компа на удобный формат( yyyy-MM-dd ) не могу победить — нужна помощь умеющих пож-та
Изменение формата даты в именах файлов
Друзья, добрый день! Подскажите пожалуйста, есть файлы с маской XXX_YYY-NAME.
Изменение даты создания папки и изменение MAC-адреса
Ребята всем привет. Нужна ваша помощь. Пишу bat для одной операции и столкнулся с проблемой что.
Смена формата вывода даты команда WMIC get creationdate
Добрый день, подскажите пожалуйста, как у команды ниже сменить формат вывода даты или возможно ли.
Изменение формата даты
Всем хорошего дня! У меня такая проблема: Написал функцию расчёта срока изготовления изделия для.
Format Windows command line date
The need for me to format date in the Windows command line environment came up when I needed to write a batch file to automatically copy the latest copies of certain files in a large folder. The files are named in the format of . YYYYMMDD.txt, which presented itself as one easy way for me to query for latest files.
Built in to Windows command line is the %date% variable, which displays the system date as follows based on my regional setting.
Please note that your regional settings might be different. For example, for those in Australia, the date might be presented in a DD/MM/YYYY format rather than the typical US MM/DD/YYYY format. If this is the case, you may wish to adjust the code below accordingly.
To suit my needs, I need to format this date to YYYYMMDD. Knowing that %date%’s format is consistent in format, we can just parse it as a string.
Bringing it together, I will have the YYYYMMDD format I am looking for.
Once again, you may need to adjust the above command based on your own regional settings.
Here is how I put this code in action in the form of a batch file that copied only the files with today’s date.
8 Replies to “Format Windows command line date”
How about explaining what the parsing syntax is doing. The answer is half baked
Thanks for visiting Dev-Notes, Len. This how string parsing works in Windows command line, assuming your variable is named %date%:
10,4% – Start with the 10th character of the string, and include the subsequent 4 characters of the string.
This thus gives us the year value out of our previously stated example of “Wed 10/08/2008”.
Also, please keep in mind that when counting characters you should start with 0 rather than 1.
Thank you, Mr Peter Chen
It’s not an answer Len… it’s a blog post offering advice. How about saying thank you and doing some research yourself?
This is nice and common knowledge.
However, what if you do logging on a device per device base and then send this logging to one fileshare.
The formatting is just a mess because different user have different regional settings in a large enterprise
Thanks C. Peter Chen. I needed to write a cmd for a Windows server that would archive log files with date-time stamps whenever my application is stop-started. Your example above got me started on the right foot. Below is the date-time string I’m using, thanks to you:
i want to print my output
abc_ddmmyyyy_00:00.txt formate
then how can write in batch file to get like this type output.
Saurabh Sharma
Saurabh, the TIME command in DOS allows you to format the output. Hope that helps.