- 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
- Как получить текущую дату и время в командной строке Windows в подходящем формате для использования в имени файла?
- 27 ответов
- Сеанс по времени, зависящий от региона,
- Примеры: (в cmd- script используйте %% вместо%)
- How do I get the day month and year from a Windows cmd.exe script?
- 14 Answers 14
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 в подходящем формате для использования в имени файла?
Обновление: теперь, когда в 2016 году я буду использовать PowerShell для этого, если у него нет убедительной обратной совместимости, особенно из-за проблем с региональными настройками с использованием date . См. @npocmaka https://stackoverflow.com/questions/203090/how-do-i-get-current-datetime-on-the-windows-command-line-in-a-suitable-format
Какие операторы командной строки Windows, которые я могу использовать для получения текущего datetime в формате, который можно поместить в имя файла?
Я хочу иметь файл .bat, который застегивает каталог в архив с текущей датой и временем как часть имени, например Code_2008-10-14_2257.zip . Есть ли какой-либо простой способ сделать это, независимо от региональных настроек машины?
На самом деле я не возражаю против формата даты, в идеале это будет yyyy-mm-dd, но все простое в порядке.
Пока у меня это есть, что на моей машине дает мне Tue_10_14_2008_230050_91 :
Я могу жить с этим, но это кажется немного неуклюжим. В идеале это было бы более кратким и иметь формат, упомянутый ранее.
Я использую Windows Server 2003 и Windows XP Professional. Я не хочу устанавливать дополнительные утилиты для достижения этого (хотя я понимаю, что есть некоторые, которые будут делать красивое форматирование даты).
27 ответов
Если вы предпочитаете время в 24-часовом/военном формате, вы можете заменить вторую строку FOR следующим образом:
Если вы хотите, чтобы дата была независимо от дневного/месячного заказа региона, вы можете использовать «WMIC os GET LocalDateTime» в качестве источника, поскольку он находится в порядке ISO:
C: > test.cmd
Местная дата [2012-06-19 10: 23: 47.048]
Сеанс по времени, зависящий от региона,
Выходной формат %DATE% и команды dir зависит от региона и, следовательно, не является ни надежным, ни умным. date.exe (часть UnxUtils) предоставляет любые дату и время в любом воображаемом формате. Вы также можете извлечь информацию о дате/времени из любого файла с помощью date.exe .
Примеры: (в cmd- script используйте %% вместо%)
date.exe +»%Y%m%d %H%M%S: Any text»
20091222 185503: Любой текст
date.exe +»Text: %y/%m/%d-any text-%H.%M»
Текст: 09/12/22 — любой текст-18.55
Command: date.exe +»%m-%d «»»%H %M %S «»»»
07-22 «18:55:03» `
Информация о дате/времени из справочного файла:
date.exe -r c:\file.txt +»The timestamp of file.txt is: %Y-%m-%d %H:%M:%S»
Используя его в CMD script, чтобы получить информацию о год, месяц, день, время:
Используя его в CMD script, чтобы получить отметку времени в любом требуемом формате:
Извлечение информации о дате/времени из любого ссылочного файла.
Добавление в файл информации о дате/времени:
date.exe часть бесплатных инструментов GNU, которые не требуют установки.
ПРИМЕЧАНИЕ. Копирование date.exe в любой каталог, находящийся в пути поиска, может привести к сбою других сценариев, которые используют встроенную команду date для Windows.
Еще два способа, которые не зависят от настроек времени (оба взяты из : как получить данные/время независимо от локализации:). И оба получают день недели, и ни один из них не требует прав администратора!:
MAKECAB — будет работать на КАЖДОЙ системе Windows (быстро, но создает небольшой временный файл) (foxidrive script):
ROBOCOPY — это не встроенная команда для Windows и XP и Windows Server 2003, но это может быть скачано с microsoft сайт. Но он встроен во все: от Windows Vista и выше:
И еще три способа использования других языков Windows script. Они придадут вам большую гибкость, например. вы можете получить неделю года, время в миллисекундах и т.д.
JScript/пакетный гибрид (необходимо сохранить как .bat ). JScript доступен на каждой системной форме NT и выше, в составе Windows script Host (хотя может быть отключен через реестр, это редкий случай):
VSCRIPT/BATCH hybrid (Возможно ли внедрить и выполнить VBScript в пакетном файле без использования временного файла?) в том же случае, что и JScript, но гибридизация не так совершенна:
PowerShell — может быть установлен на всех компьютерах с .NET-загрузкой из Microsoft (v1, v2, v3 (только для Windows 7 и выше )). Он по умолчанию установлен на все: от Windows 7/Windows Server 2008 и выше:
Чтобы использовать его из пакетного файла:
Скомпилированный jscript.net/batch (никогда не видел Windows-компьютер без .NET, поэтому я думаю, что это довольно портативный):
Logman Это не может получить год и день недели. Он сравнительно медленный, а также создает временный файл и основан на отметках времени, которые logman ставит на свои файлы журналов. Он будет работать на всех, начиная от Windows XP и выше. Вероятно, он никогда не будет использоваться кем-либо — включая меня — но это еще один способ.
Еще один способ: WMIC, который также дает неделю года и день недели, но не миллисекунды (для миллисекундного ответа на запрос foxidrive):
С помощью TYPEPERF с некоторыми усилиями быть быстрыми и совместимыми с различными языковыми настройками и как можно быстрее:
MSHTA позволяет вызывать методы JavaScript, похожие на метод JScript, продемонстрированный в № 3 выше. Имейте в виду, что свойства объекта JavaScript Date с месячными значениями нумеруются от 0 до 11, а не от 1 до 12. Таким образом, значение 9 означает октябрь.
How do I get the day month and year from a Windows cmd.exe script?
How do I get the current day month and year from inside a Windows cmd script? I need to get each value into a separate variable.
14 Answers 14
A variant of script that works locale-independently. Put it in a text file with .cmd extension and run.
The variables %dd%, %mm% and %yy% will keep the day(‘DD’ format), the month(‘MM’ format) and the year(‘YYYY’ format) respectively.
To get the year, month, and day you can use the %date% environment variable and the :
operator. %date% expands to something like Thu 08/12/2010 and :
allows you to pick up specific characters out of a variable:
Use %time% in similar fashion to get what you need from the current time.
set /? will give you more information on using special operators with variables.
begining_char,number_of_chars, thus if date is 2021-02-30 to get year it should be : set year=%date:
0,4% – Bomba Ps Feb 3 at 9:02
The following batch code returns the components of the current date in a locale-independent manner and stores day, month and year in the variables CurrDay , CurrMonth and CurrYear , respectively:
There are two nested for /F loops to work around an issue with the wmic command, whose output is in unicode format; using a single loop results in additional carriage-return characters which impacts proper variable expansion.
Since day and month may also consist of a single digit only, I prepended a leading zero 0 in the loop construct. Afterwards, the values are trimmed to always consist of two digits.
7 is starting position 2 number of digits to display
6,4% . Thinking about how Windows was designed (or could be designed), locality independency seems something difficult to achieve with a simple piece of code. That is not a problem for Linux or Unixes in general, though. – Antônio Medeiros May 12 ’17 at 12:26
LANGUAGE INDEPENDENCY:
The Andrei Coscodan solution is language dependent, so a way to try to fix it is to reserve all the tags for each field: year, month and day on target languages. Consider Portugese and English, after the parsing do a final set as:
Look for the year setting, I used both tags from English and Portuguese, it worked for me in Brazil where we have these two languages as the most common in Windows instalations. I expect this will work also for some languages with Latin origin like as French, Spanish, and so on.
Well, the full script could be:
I hope this helps someone that deal with diferent languages.
The only reliably way I know is to use VBScript to do the heavy work for you. There is no portable way of getting the current date in a usable format with a batch file alone. The following VBScript file
and this batch snippet
should work, though.
While you can get the current date in a batch file with either date /t or the %date% pseudo-variable, both follow the current locale in what they display. Which means you get the date in potentially any format and you have no way of parsing that.
This variant works for all localizations:
I think that Andrei Coscodan answer is the best when you can’t make many assumptions. But sometimes having a one-liner is nice if you can make some some assumptions. This solution assumes that ‘date \t’ will return one of two formats. On WindowsXP ‘date /t ‘returns «11/23/2011», but on Windows7 it returns «Wed 11/23/2011».
Thanks to Andrei Consodan answer to help me with this one-line solution.
I have converted to using Powershell calls for this purpose in my scripts. It requires script execution permission and is by far the slowest option. However it is also localization independent, very easy to write and read, and it is much more feasible to perform adjustments to the date like addition/subtraction or get the last day of the month, etc.
Here is how to get the day, month, and year
Or, here is yesterday’s date in yyyy-MM-dd format
for /f %%i in (‘»powershell (Get-Date).AddDays(-1).ToString(\»yyyy-MM-dd\»)»‘) do set yesterday=%%i
Day of the week
for /f %%d in (‘»powershell (Get-Date).DayOfWeek»‘) do set DayOfWeek=%%d
Current time plus 15 minutes
for /f %%i in (‘»powershell (Get-Date).AddMinutes(15).ToString(\»HH:mm\»)»‘) do set time=%%i
Try using for wmic OS Get localdatetime^|find «.» in for /f without tokens and/or delims , this works in any language / region and also, no user settings interfere with the layout of the output.
- With Hour and Minute in bat/cmd file:
- With Hour and Minute in command line:
Extract Day, Month and Year
The highest voted function and the accepted one do NOT work locale-independently since the DATE command is subject to localization too. For example (the accepted one): In English you have YYYY for year and in Holland it is JJJJ. So this is a no-go. The following script takes the users’ localization from the registry, which is locale-independent.
Extract only the Year
For a script I wrote I wanted only to extract the year (locale-independent) so I came up with this oneliner as I couldn’t find any solution. It uses the ‘DATE’ var, multiple delimiters and checks for a number greater than 31. That then will be the current year. It’s low on resources in contrast to some of the other solutions.