Windows command line date command

Regionally independent date time parsing

The output format of %DATE% and of the dir command is regionally dependent and thus neither robust nor smart. date.exe (part of UnxUtils) delivers any date and time information in any thinkable format. You may also extract the date/time information from any file with date.exe.

Examples: (in a cmd-script use %% instead of %)

date.exe +"%Y-%m-%d"
2009-12-22

date.exe +"%T"
18:55:03

date.exe +"%Y%m%d %H%M%S: Any text"
20091222 185503: Any text

date.exe +"Text: %y/%m/%d-any text-%H.%M"
Text: 09/12/22-any text-18.55

Command: date.exe +"%m-%d """%H %M %S """"
07-22 «18:55:03″`

The date/time information from a reference file:
date.exe -r c:\file.txt +"The timestamp of file.txt is: %Y-%m-%d %H:%M:%S"

Using it in a CMD script to get year, month, day, time information:

for /f "tokens=1,2,3,4,5,6* delims=," %%i in ('C:\Tools\etc\date.exe +"%%y,%%m,%%d,%%H,%%M,%%S"') do set yy=%%i& set mo=%%j& set dd=%%k& set hh=%%l& set mm=%%m& set ss=%%n

Using it in a CMD script to get a timestamp in any required format:

for /f "tokens=*" %%i in ('C:\Tools\etc\date.exe +"%%y-%%m-%%d %%H:%%M:%%S"') do set timestamp=%%i

Extracting the date/time information from any reference file.

for /f "tokens=1,2,3,4,5,6* delims=," %%i in ('C:\Tools\etc\date.exe -r file.txt +"%%y,%%m,%%d,%%H,%%M,%%S"') do set yy=%%i& set mo=%%j& set dd=%%k& set hh=%%l& set mm=%%m& set ss=%%n

Adding to a file its date/time information:

for /f "tokens=*" %%i in ('C:\Tools\etc\date.exe -r file.txt +"%%y-%%m-%%d.%%H%%M%%S"') do ren file.txt file.%%i.txt

date.exe is part of the free GNU tools which need no installation.

NOTE: Copying date.exe into any directory which is in the search path may cause other scripts to fail that use the Windows built-in date command.

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

Бывает, что некоторые команды Windows cmd сложно вспомнить, и сохранение их на компьютере или на бумаге в качестве шпаргалки является хорошей практикой. Этот список не является полным, но он содержит наиболее часто используемые команды. Не стесняйтесь добавить свои наиболее часто используемые команды в комментариях ниже, а так же поделиться этим списком.

Управление файлами и папками

  • COPY – Копирование файлов в другое место
  • DIR – Отображение файлов и папок в текущем каталоге
  • DEL или ERASE – Удаление файлов
  • EDIT – Запуск редактора файлов
  • CD – Изменить каталог
  • EXPAND – Распаковать сжатые файлы
  • FC – Сравнивает файлы и показывает различия между ними
  • FIND – Найти текстовую строку в файле
  • MD или MAKEDIR – Создать папку
  • MOVE – Переместить файлы из одной папки в другую
  • PRINT – отобразить содержимое текстового файла
  • RD или RMDIR – удалить папку
  • REN или RENAME – переименовать файл или папку
  • REPLACE – Замена файлов в одном каталоге на файлы с тем же именем в другом каталоге
  • ROBOCOPY – Использует программу «Робокопи» для копирования файлов и каталогов
  • TREE – Показывает структуру каталогов диска или папки
  • TYPE – Отображает содержимое текстовых файлов
  • OPENFILES – Управление открытыми локальными или сетевыми файлами
  • XCOPY – Копирование файлов и деревьев каталогов

Приложения и процессы

  • SCHTASKS – Запланированный запуск приложения приложения (планировщик задач)
  • SHUTDOWN – Выключение или перезагрузка компьютера
  • TASKLIST – Список выполняемых задач
  • TASKKILL – Остановить или прекратить выполнение задачи (для остановки задачи используется PID, который можно узнать из TASKLIST).
  • REG – Запустить редактор реестра
  • RUNAS – Запуск задачи от имени другого пользователя

Управление дисками

  • CHKDISK – Проверяет диск и показывает статистику
  • DEFRAG – Запуск дефрагментации диска
  • CHKNTFS – Отображает или изменяет выполнение проверки диска при загрузке
  • COMPACT – Отображает и изменяет сжатие файлов в разделах NTFS
  • CONVERT – преобразование дискового тома FAT в NTFS
  • DISKPART – Отображение и настройка свойств разделов диска
  • FORMAT – Форматирование диска
  • FSUTIL – Отображение и настройка свойств файловой системы
  • LABEL – Создание, изменение или удаление метки тома диска
  • RECOVER – Восстановление данных с поврежденного или испорченного диска
  • VOL – Отображение метки тома и серийного номера диска

Системная информация

  • DATE – Выводит или устанавливает текущую дату
  • TIME – Выводит или устанавливает системное время
  • DRIVERQUERY – Отображает текущее состояние и свойства драйвера устройства
  • HOSTNAME – Отображает имя компьютера
  • SYSTEMINFO – Отображает информацию о конфигурации компьютера
  • VER – Позволяет просмотреть версию Windows
  • GPRESULT – Отображает текущие примененные групповые политики (RSoP)
  • GPUPDATE – Обновление групповых политик

Сеть

  • IPCONFIG – Отображает информацию о сетевых интерфейсах
  • PING – Отправляет ICMP-запросы на целевой хост, проверяет его доступность
  • TRACERT – Отображение пути пакетов в сети
  • NSLOOKUP – Поиск IP-адреса по имени ресурса
  • ROUTE – Отображает таблицы сетевых маршрутов
  • ARP – Показывает таблицу с IP-адресами, преобразованными в физические адреса
  • NETSH – Запускает программу управления сетевыми настройками
  • GETMAC – Показывает MAC-адрес сетевого адаптера
  • TFTP – Запускает TFTP-клиент в консоли

Настройка командной строки

  • CLS – Очистить экран
  • CMD – Отображает другую командную строку
  • COLOR – Устанавливает цвет текста и фона в консоли
  • PROMPT – Изменение начального текста командной строки
  • TITLE – Присвоение заголовка для текущего сеанса
  • HELP – Запуск справки CMD
  • EXIT – Выход из командной строки

Аverage rating : 4.9

Оценок: 12

191028
Санкт-Петербург
Литейный пр., д. 26, Лит. А

+7 (812) 403-06-99

700
300

ООО «ИТГЛОБАЛКОМ ЛАБС»

191028
Санкт-Петербург
Литейный пр., д. 26, Лит. А

+7 (812) 403-06-99

700
300

ООО «ИТГЛОБАЛКОМ ЛАБС»

700
300

Very easy to get the date and time, actually:

set Year=
for /f "skip=2" %%x in ('wmic Path Win32_LocalTime get Year^,Month^,Day^,Hour^,Minute^,Second /Format:List') do (
  if not defined Year set %%x
)

I’m assuming local time here. If you need UTC, adapt it accordingly.

Your format makes things more complicated. Apologies if I get something wrong here, I’m not familiar with am/pm formats.

if %Hour% LSS 12 (
  set ampm=AM
  if %Hour%==0 set Hour=12
) else (
  set ampm=PM
  set /a Hour-=12
)

We need a few leading zeroes:

if %Month% LSS 10 set Month=0%Month%
if %Day% LSS 10 set Day=0%Day%
if %Minute% LSS 10 set Minute=0%Minute%
if %Hour% LSS 10 set Hour=0%Hour%

Then it’s time to assemble the parts:

set Timestamp=%Month%-%Day%-%Year% %Hour%:%Minute% %ampm%

(Just a random note: Why on earth would you want that timestamp format?)

Updated: 12/31/2020 by

date command

The date command can view or change the current date of the system clock.

Command syntax

The following is the syntax of the date command.

Windows Vista and later

date [ /t | date ]

Type date without parameters to display the current date setting and a prompt for a new date. Press Enter to keep the same date.

If you provide a date in the format MM-DD-YY, the system date is set to that date.

Tip

When specifying a two-digit year, the digits 00-99 correspond to the years 1980-2099.

In modern versions of Windows, the date command accepts a four-digit date, e.g., MM-DD-YYYY.

With the /t switch, the date command displays the system date, without prompting for a new one.

Windows XP and earlier

In Windows XP and previous versions of Windows, the /t switch is not supported.

DATE [ date ]

Type date without parameters to display the current date setting and a prompt for a new date. Press Enter to keep the same date. Provide a date as MM-DD-YY to set the system date to that date.

Examples

date

Display the current date and prompt for a new date.

The current date is: Sat 05/09/2020
Enter the new date: (mm-dd-yy)

If you enter a new date in the format MM-DD-YY, the system date is set to that date, if you are using an elevated Command Prompt.

If you press Enter without typing a date, the current system date is not changed, and the command exits.

date 05-08-20

The command above sets the system date to March 8, 2020, in an elevated command prompt.

date /t

Displays the current system date.

Sat 05/09/2020

Availability

Date is an internal command available in the following Microsoft operating systems.

  • MS-DOS 5.0 and above
  • Windows 95
  • Windows 98
  • Windows ME
  • Windows NT
  • Windows 2000
  • Windows XP
  • Windows Vista
  • Windows 7
  • Windows 8
  • Windows 10

  • Windows command line execute command
  • Windows cannot find make sure you typed the name correctly and then try again перевод
  • Windows cannot find google chrome
  • Windows cannot find bin javaw
  • Windows cannot copy files required for installation