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
@echo off
for /F "tokens=2" %%i in ('date /t') do set mydate=%%i
set mytime=%time%
echo Current time is %mydate%:%mytime%
When we run the above batch file
C:\>datetime.cmd Current time is 08/12/2015:22:57:24.62 C:\>
Get date from command line
To print today’s date on the command prompt, we can run date /t.
c:\>date /t Thu 05/14/2015 c:\>
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.
c:\>date The current date is: Sat 05/16/2015 Enter the new date: (mm-dd-yy) c:\>
In addition to date command, we also have an environment variable using which we can find today’s date.
c:\>echo %date% Sun 05/17/2015
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.
for /F "tokens=2" %i in ('date /t') do echo %i
Example:
c:\>for /F "tokens=2" %i in ('date /t') do echo %i
05/14/2015
c:\>
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.
c:\>time /t 11:17 PM c:\>time The current time is: 23:17:18.57 Enter the new time: c:\>
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.
c:\>echo %time% 23:23:51.62 c:\>
Get date and time
c:\>echo %date%-%time% Sun 05/17/2015-23:21:03.34
Вывести в текстовый файл текущую дату и время
Иногда требуется программно вывести дату и время в файл текстового формата *.txt, *.dat или с любым другим расширением для последующей обработки. Для этих целей можно использовать средства операционной системы, в частности командную строку Windows и глобальные переменные содержащие время с датой.
Следуйте инструкции ниже чтобы записать в файл локальное текущее дату и время
Выводим текущую дату и время в файл
- Откройте консоль «CMD» нажатием на Пуск->Выполнить->пишем cmd и жмем клавишу «Enter». Откроется черное окошко, это консоль Windows. Прописываем команду «echo Local date: %date% — Time: %time%>C:\date.txt
Открываем консоль CMD
«
- Команда, которую мы прописали, создает текстовый файл на диске «C:\» и записывает в него локальное текущее время и дату вида: «Local date: 26.05.2018 — Time: 15:23:05,12»
Ввод команды и просмотр файла с данными
Для вывода мы используем глобальные переменные вида %date% и %time%, первая переменная содержит дату, вторая соответственно время с миллисекундами.
Вы можете поменять путь, где будет создаваться текстовый файл, а так же сменить расширение и отформатировать строку по-своему желанию. Помните что переменные нужно обрамлять текстом на латинице, если хотите записать в файл кириллицу, для этого перед основной командой используйте команду «chcp 1251» для смены кодировки, в противном случае русский текст будет превращен в непонятные символы.
-
Using the %DATE% and %TIME% Variables
-
Formatting Date and Time
-
Combining Date and Time
-
Conclusion
-
FAQ
Getting the current date and time in a Batch Script is an essential skill for anyone looking to automate tasks on Windows. Whether you’re logging events, creating backups, or simply needing to timestamp files, understanding how to retrieve this information can streamline your workflow.
In this article, we’ll explore various methods to obtain the date and time using Batch Script with clear code examples. By the end, you’ll have a solid grasp of how to effectively utilize these commands in your scripts, making your automation tasks more efficient and organized.
Using the %DATE% and %TIME% Variables
The simplest way to get the current date and time in a Batch Script is by using the built-in environment variables %DATE% and %TIME%. These variables automatically fetch the system’s current date and time when called.
Here’s how you can use them:
@echo off
set currentDate=%DATE%
set currentTime=%TIME%
echo Current Date: %currentDate%
echo Current Time: %currentTime%
Output:
Current Date: Wed 10/11/2023
Current Time: 14:45:30.12
In this example, we first turn off the command echoing with @echo off for cleaner output. We then set two variables: currentDate and currentTime, which store the values of %DATE% and %TIME%, respectively. Finally, we print these variables to the console. The output will display the current date and time in the format specified by your system’s regional settings. This method is quick and straightforward, making it ideal for simple scripts where you need the date and time without additional formatting.
Formatting Date and Time
While the %DATE% and %TIME% variables are handy, you might need the date and time in a specific format for logging or file naming purposes. To achieve this, you can manipulate the output using string operations.
Here’s an example that formats the date and time:
@echo off
for /f "tokens=1-3 delims=/ " %%a in ("%DATE%") do (
set day=%%a
set month=%%b
set year=%%c
)
for /f "tokens=1-2 delims=: " %%a in ("%TIME%") do (
set hour=%%a
set minute=%%b
)
set formattedDate=%year%-%month%-%day%
set formattedTime=%hour%-%minute%
echo Formatted Date: %formattedDate%
echo Formatted Time: %formattedTime%
Output:
Formatted Date: 2023-10-11
Formatted Time: 14-45
In this script, we use for /f loops to parse the %DATE% and %TIME% outputs. The delims option specifies the characters used to split the input. We then assign the parsed values to new variables for day, month, year, hour, and minute. Finally, we create formatted strings for the date and time, which are printed out. This method allows you to customize the output to fit your needs, making it suitable for scenarios like creating timestamped logs or files.
Combining Date and Time
Sometimes, you may want to combine the date and time into a single string for logging or display purposes. This can be done easily by concatenating the formatted strings.
Here’s how you can do it:
@echo off
setlocal enabledelayedexpansion
for /f "tokens=1-3 delims=/ " %%a in ("%DATE%") do (
set day=%%a
set month=%%b
set year=%%c
)
for /f "tokens=1-2 delims=: " %%a in ("%TIME%") do (
set hour=%%a
set minute=%%b
)
set combinedDateTime=!year!-!month!-!day! !hour!:!minute!
echo Combined Date and Time: !combinedDateTime!
Output:
Combined Date and Time: 2023-10-11 14:45
In this script, we again extract the date and time components using for /f loops. Here, we use setlocal enabledelayedexpansion to allow the use of ! for variable expansion inside a loop. We then concatenate the date and time into a single variable called combinedDateTime. The output is a neatly formatted string that combines both elements, making it perfect for logs or other applications where a timestamp is required.
Conclusion
In this article, we covered several methods to retrieve the current date and time in Batch Script. From using simple environment variables to formatting and combining them for specific needs, these techniques will enhance your scripting skills and improve your automation tasks. Whether you’re logging events or creating dynamic file names, having the ability to manipulate date and time in Batch Script is invaluable. By implementing these examples, you can take your scripting to the next level and create more effective and organized scripts.
FAQ
-
How can I get the date in a different format?
You can manipulate the output of the%DATE%variable using string operations in Batch Script to achieve your desired format. -
Can I use these methods in a scheduled task?
Yes, you can use these Batch Script techniques in scheduled tasks to log information or perform actions based on the current date and time. -
What if my system date format is different?
The output of%DATE%can vary based on regional settings. You may need to adjust the parsing logic accordingly. -
Is it possible to save the date and time to a file?
Yes, you can redirect the output of your Batch Script to a file using the>operator, allowing you to save the date and time. -
Can I use these commands in a command prompt directly?
Yes, you can run these commands directly in the command prompt for quick checks of the date and time.
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Иногда требуется сформировать переменную даты и времени в 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:~0,2%
set m=%TIME:~3,2%
set s=%TIME:~6,2%
set ms=%TIME:~9,2%
set curtime=%h%:%m%:%s%:%ms%
set dd=%DATE:~0,2%
set mm=%DATE:~3,2%
set yyyy=%DATE:~6,4%
set curdate=%dd%-%mm%-%yyyy%
set curdatetime=%curdate% %curtime%
echo Текущее время — %curdatetime%
В некоторых версиях Windows формат выдачи даты и времени другой, поэтому данный скрипт может работать совсем так как нам нужно.
По идее, подобным способом можно брать части любых переменных, суть в том что формат здесь такой:
%DATE:~3,2%
Первая цифра после :~ — это номер символа, с которого мы начинаем брать значение, вторая цифра это сколько символов захватывать.
Таким образом получается что мы можем взять для своих нужд любую часть, любой доступной нам переменной среды Windows.
Мне известны следующие переменные, значения которых мы можем получить:
Имя
| ALLUSERSPROFILE | Возвращает размещение профиля «All Users». |
| APPDATA | Возвращает используемое по умолчанию размещение данных приложений. |
| CD | Указывает путь текущей папки. Идентична команде CD без аргументов. |
| CMDCMDLINE | точная команда использованная для запуска текущего cmd.exe. |
| CMDEXTVERSION | версия текущего Command Processor Extensions. |
| CommonProgramFiles | Расположение каталога «Common Files» (обычно %ProgramFiles%\Common Files) |
| COMPUTERNAME | имя компьютера |
| COMSPEC | путь до исполняемого файла shell |
| DATE | Возвращает текущую дату. Использует тот же формат, что и команда date /t. Создается командой Cmd.exe. |
| ERRORLEVEL | Возвращает код ошибки последней использовавшейся команды. Значение, не равное нулю, обычно указывает на наличие ошибки. |
| HOMEDRIVE | Возвращает имя диска локальной рабочей станции, связанного с основным каталогом пользователя. Задается на основании расположения основного каталога. Основной каталог пользователя указывается в оснастке «Локальные пользователи и группы». |
| HOMEPATH | Возвращает полный путь к основному каталогу пользователя. Задается на основании расположения основного каталога. Основной каталог пользователя указывается в оснастке «Локальные пользователи и группы». |
| HOMESHARE | Возвращает сетевой путь к общему основному каталогу пользователя. Задается на основании расположения основного каталога. Основной каталог пользователя указывается в оснастке «Локальные пользователи и группы». |
| LOGONSERVER | имя контроллера домена, использовавшегося для авторизации текущего пользователя |
| NUMBER_OF_PROCESSORS | количество процессоров в системе |
| OS | название операционной системы. Windows XP и Windows 2000 отображаются как Windows_NT. |
| PATH | Указывает путь поиска для исполняемых файлов. |
| PATHEXT | Возвращает список расширений файлов, которые рассматриваются операционной системой как исполняемые. |
| PROCESSOR_ARCHITECTURE | архитектура процессора |
| PROCESSOR_IDENTIFIER | описание процессора |
| PROCESSOR_LEVEL | номер модели процессора |
| PROCESSOR_REVISION | ревизия процессора |
| PROGRAMFILES | путь к папке Program Files |
| PROMPT | Возвращает параметры командной строки для текущего интерпретатора. Создается командой Cmd.exe. |
| RANDOM | случайное десятичное число от 0 до 32767. Генерируется Cmd.exe |
| SESSIONNAME | Тип сессии. Значение по умолчанию «Console» |
| SYSTEMDRIVE | диск на котором расположена корневая папка Windows |
| SYSTEMROOT | путь к корневой папке Windows |
| TEMP or TMP | Возвращает временные папки, по умолчанию используемые приложениями, которые доступны пользователям, выполнившим вход в систему. Некоторые приложения требуют переменную TEMP, другие — переменную TMP. Потенциально TEMP и TMP могут указывать на разные каталоги, но обычно — совпадают. |
| TIME | Возвращает текущее время. Использует тот же формат, что и команда time /t. Создается командой Cmd.exe. |
| USERDOMAIN | имя домена, которому принадлежит текущий пользователь |
| USERNAME | имя текущего пользователя |
| USERPROFILE | путь к профайлу текущего пользователя |
| WINDIR | директория в которую установлена Windows |
Описание
