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» для смены кодировки, в противном случае русский текст будет превращен в непонятные символы.
Иногда требуется сформировать переменную даты и времени в 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 |
Описание
В современных компьютерах сменить дату и время не составляет большого труда, достаточно перейти в панель задач. Также вы можете проделать это через командную строку и не заметно для пользователя.
Запускаем командную строку («Win+R» — «cmd») и набираем «time«, после пробела ставим желаемую дату в формате ЧЧ:MM:СС, жмем Enter и смотрим в трей.
Пример:
time 15:38:00
Аналогичные действия проделываем и с датой, вот только вместо time набираем — «date» и саму дату в формате ЧЧ.ММ.ГГГГ:
date 14.04.2016
Получить список часовых поясов
TZUTIL /l
Получить информацию о часовом поясе на данном ПК
TZUTIL /g
Установить часовой пояс
TZUTIL /s "Yakutsk Standard Time"
The «windows time cmd» commands allow users to view and modify the system time and date directly from the Command Prompt.
time
This command will prompt you to enter a new time, or if run without parameters, it will display the current system time.
Understanding the CMD Time Command
What is the CMD Time Command?
The CMD time command is a built-in command in Windows that allows users to view and modify the system’s time settings. This command plays a crucial role, especially for system administrators who need to ensure that the time settings are accurate for logging, scheduling tasks, and maintaining proper functioning of networked services. The time command is straightforward yet powerful, geared toward enhancing time management within the Windows operating environment.
How to Access CMD
Accessing the Command Prompt (CMD) is the first step in utilizing the windows time cmd capabilities. You can open CMD through several methods:
- Using Run: Press `Windows + R`, type in `cmd`, and hit Enter.
- Via Search: Click on the search icon on the taskbar, type `cmd`, and select the Command Prompt app.
- Through File Explorer: Open Windows Explorer, navigate to `C:\Windows\System32`, and double-click on `cmd.exe`.
Once the Command Prompt is visible, you are ready to start executing commands.
Mastering Windows Uptime Cmd for Quick Checks
Basic Usage of the Time Command
Displaying the Current System Time
To view the current system time, you can simply enter:
time
Upon executing this command, CMD will display the current time in hours, minutes, and seconds format. This is a quick way to check the system’s time without needing to navigate through the user interface.
Setting the Time
Changing the System Time
The ability to set the system time can be essential in multiple scenarios, particularly in an administrative context. The syntax for changing the time is as follows:
time HH:MM:SS
For instance, if you want to set the time to 2:30 PM (14:30), you would type:
time 14:30:00
When you set the time, CMD will prompt for confirmation, requiring you to debug any input errors. Ensure you use the 24-hour format to avoid confusion with AM and PM designations.
Tips for Input Format
While setting the time, it’s crucial to note the following tips to avoid common pitfalls:
- Always use the 24-hour format (e.g., 14:00 for 2 PM).
- If you attempt to set the time to an incorrect format, CMD will notify you and prompt you to re-enter.
Mastering Windows XP Cmd: Quick Commands to Enhance Your Skills
Advanced Time Command Functions
Synchronizing Time with a Time Server
Time synchronization is essential for maintaining consistency across systems, particularly in business environments. Utilization of the `net time` command makes this synchronization possible. The syntax is as follows:
net time \\time-server-name /set
Replace `time-server-name` with the actual name or address of the time server you wish to sync with. This command pulls the accurate time from the specified server, ensuring that all systems on the network maintain consistent time.
Creating a Batch File for Time Management
Automating time display using a batch file can streamline various tasks. Here’s a simple example of how to create a batch file that displays the current system time at regular intervals.
- Open Notepad and paste the following script:
@echo off
:start
echo Current Time: %time%
timeout /t 60
goto start
- Save the file with a `.bat` extension, such as `show_time.bat`.
This script will display the current time and refresh every 60 seconds. It utilizes the `timeout` command to wait before displaying the time again. This automation can be handy for monitoring time-sensitive tasks.
Mastering Windows 10 Cmd: Quick Tips for Power Users
Troubleshooting Common Issues
Error Messages When Using Time Command
While using the windows time cmd, you may encounter error messages related to incorrect formats or insufficient permissions. Common error messages include «Invalid time» and «Access Denied.» When faced with such messages, verify your command syntax and ensure you have the necessary permissions to make changes to the system time.
Permissions Required for Setting Time
Changing the system time typically requires administrative privileges. If you receive «Access Denied» messages, try running CMD as an Administrator:
- Search for `cmd` in the start menu.
- Right-click on Command Prompt and select «Run as Administrator.»
This will grant the necessary permissions to set the system time without restrictions.
Mastering Windows 10 Cmd Prompt: A Quick Guide
Practical Applications of the CMD Time Command
Synchronizing Time for Networked Systems
In corporate environments, where multiple computers operate in a network, it’s vital to maintain time consistency. Time discrepancies can lead to issues with file timestamps, logging, and scheduling tasks. Using the windows time cmd to establish synchronization with a reliable time server prevents these issues and promotes operational fluidity.
Time Stamping for Documentation
Incorporating timestamps into your documentation is crucial for maintaining accurate records. You can easily timestamp log entries with a simple command:
echo [%date% %time%] Log Entry >> logfile.txt
This command appends a new log entry to `logfile.txt`, complete with the current date and time. This practice can be extremely useful for tracking changes, debugging information, or maintaining records of transactions and activities.
Windows 10 Cmd Recovery: Quick Guide for Every User
Frequently Asked Questions
Can I Schedule Time Commands?
You can schedule CMD commands, including the time command, to run at specific intervals using Task Scheduler. By creating a scheduled task, you can automate operations that require time checks or adjustments regularly.
Are There Limitations to the Time Command?
Yes, while the time command is quite useful, it does have limitations, such as not supporting time zone changes directly. Instead, adjustments usually need to be handled through the system settings.
Can I Use the Time Command in PowerShell?
The time command is native to CMD; however, you can execute similar commands in PowerShell. For example, getting the current time can be done with `Get-Date`. The versatility of CMD and PowerShell allows you to choose the tool best suited to your workflow.
Mastering Windows 11 Cmd Commands: A Quick Guide
Conclusion
The windows time cmd command provides a fundamental yet robust tool for managing system time within a Windows environment. Understanding its basic usage, advanced functions, and various applications can significantly enhance your system management capabilities. Whether you’re a novice eager to learn or an experienced administrator refining your skills, mastering the time command will undoubtedly contribute to your efficiency and effectiveness in various tasks.