Командная строка windows текущее время

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 и глобальные переменные содержащие время с датой.

Следуйте инструкции ниже чтобы записать в файл локальное текущее дату и время

Выводим текущую дату и время в файл

  1. Откройте консоль «CMD» нажатием на Пуск->Выполнить->пишем cmd и жмем клавишу «Enter». Откроется черное окошко, это консоль Windows. Прописываем команду «echo Local date: %date% — Time: %time%>C:\date.txt

    Открываем консоль CMD

    Открываем консоль CMD

    «

  2. Команда, которую мы прописали, создает текстовый файл на диске «C:\» и записывает в него локальное текущее время и дату вида: «Local date: 26.05.2018 — Time: 15:23:05,12»

    Ввод команды и просмотр файла с данными

    Ввод команды и просмотр файла с данными

Для вывода мы используем глобальные переменные вида %date% и %time%, первая переменная содержит дату, вторая соответственно время с миллисекундами.

Вы можете поменять путь, где будет создаваться текстовый файл, а так же сменить расширение и отформатировать строку по-своему желанию. Помните что переменные нужно обрамлять текстом на латинице, если хотите записать в файл кириллицу, для этого перед основной командой используйте команду «chcp 1251» для смены кодировки, в противном случае русский текст будет превращен в непонятные символы.

You can use the date and
time commands on a Microsoft Windows system to
display current date and time information:

C:\Users\Lila>date /t
Sat 08/26/2017

C:\Users\Lila>time /t
02:07 PM

C:\Users\Lila>

Placing /t after the commands results in the current date
and time information being displayed without an accompanying prompt to change
the current settings.

You can display the information in a different format using
the
Windows Management Instrumentation Command-line (WMIC) command shown below:

C:\Users\Lila>wmic path win32_utctime get * /format:list


Day=26
DayOfWeek=6
Hour=18
Milliseconds=
Minute=16
Month=8
Quarter=3
Second=19
WeekInMonth=4
Year=2017




C:\Users\Lila>

The output will show the day and the number for the day of the week,
e.g., 6 for Saturday (the numbering starts with Monday as the first day of
the week). The WMIC command also shows the number of seconds, the quarter of
the year, and the week in the current month, which are not shown by the time
command.

The hour is displayed in
24-hour clock time, aka «military time.» In the example above, since
the local time is 2:07 PM, the hour value is 18, because two o’clock is
14:00 in 24-hour clock time with 4 hours added to the number of hours to make
the value 18, since the system is in the
Eastern Time Zone
, currently Eastern Daylight Time (EDT), in the United States, which is
currently 4 hours behind
Coordinated
Universal Time, which is abbreviated as UTC. There is a 5 hour time
difference when Eastern Standard Time (EST) applies. You can see the
current U.S. time zones at
Time Zones Currently Being Used in United States.

You can find the time zone the Windows system is in with the command shown
below:

C:\>systeminfo | find "Time Zone:"
Time Zone:                 (UTC-05:00) Eastern Time (US & Canada)

C:\>

The command above shows there is a 5 hour difference between the time zone
the system is in and UTC time, aka Zulu time or GMT, but that is only the
case when Eastern Standard Time (EST) is in effect, not when Eastern Daylight
Time (EDT) is in effect.

If you omit the /format:list parameter at the end of the
wmic path win32_utctime get * command, all of the values will be
displayed on one line:

C:\>wmic path win32_utctime get *
Day  DayOfWeek  Hour  Milliseconds  Minute  Month  Quarter  Second  WeekInMonth  Year
26   6          18                  32      8      3        11      4            2017


C:\>

You can also specify the particular values you are interested rather than
getting all values with the asterisk. E.g.:

C:\>wmic path win32_utctime get hour, minute, second
Hour  Minute  Second
18    34      47


C:\>wmic path win32_utctime get quarter
Quarter
3


C:\>wmic path win32_utctime get weekinmonth
WeekInMonth
4


C:\>wmic path win32_utctime get hour, minute, second
Hour  Minute  Second
18    35      13


C:\>

If I want to know whether
daylight saving
time (DST) is currently in effect, I can open a
PowerShell
window and use the command shown below:

PS C:\Users\Lila> Get-CimInstance Win32_TimeZone | select *


Caption               : (UTC-05:00) Eastern Time (US & Canada)
Description           : (UTC-05:00) Eastern Time (US & Canada)
SettingID             :
Bias                  : -300
DaylightBias          : -60
DaylightDay           : 2
DaylightDayOfWeek     : 0
DaylightHour          : 2
DaylightMillisecond   : 0
DaylightMinute        : 0
DaylightMonth         : 3
DaylightName          : Eastern Daylight Time
DaylightSecond        : 0
DaylightYear          : 0
StandardBias          : 0
StandardDay           : 1
StandardDayOfWeek     : 0
StandardHour          : 2
StandardMillisecond   : 0
StandardMinute        : 0
StandardMonth         : 11
StandardName          : Eastern Standard Time
StandardSecond        : 0
StandardYear          : 0
PSComputerName        :
CimClass              : root/cimv2:Win32_TimeZone
CimInstanceProperties : {Caption, Description, SettingID, Bias...}
CimSystemProperties   : Microsoft.Management.Infrastructure.CimSystemProperties



PS C:\Users\Lila>

The StandardHour, StandardDay,
StandardDayOfWeek, and StandardMonth values tell me
when standard time goes into effect on this system. Since
StandardMonth is 11, I know that it takes effect in November. The
StandardDayofWeek value is zero, which indicates the change occurs
on the first day of the week, i.e., Sunday and the StandardDay
value of 1 indicates that the change occurs on the first Sunday of
StandardMonth, i.e., the first Sunday in November. The
StandardHour value of 2 tells me the time change takes place
at 2:00 AM on that day, i.e., the change occurs on the first Sunday in
November at 2:00 AM.

Likewise, I can examine the «Daylight» values to determine when daylight
savings time begins:

DaylightDay           : 2
DaylightDayOfWeek     : 0
DaylightHour          : 2
DaylightMillisecond   : 0
DaylightMinute        : 0
DaylightMonth         : 3

I can see from the above that, for this system, daylight savings time
begins on the second Sunday of March at 2:00 AM EST when clocks are
advanced one hour to 3:00 AM EDT, leaving a one hour gap. The mnemonic
for the time changes is «spring forward, fall back.» You can see the
calendar dates for daylight saving time for recent years and future years at

Daylight saving time in the United States.

You can select individual values by specifying the value you are interested
in instead of using an asterisk after «select». E.g.:

PS C:\Users\Lila> Get-CimInstance Win32_TimeZone | select DaylightName

DaylightName
------------
Eastern Daylight Time


PS C:\Users\Lila> Get-CimInstance Win32_TimeZone | select DaylightName, StandardName

DaylightName          StandardName
------------          ------------
Eastern Daylight Time Eastern Standard Time


PS C:\Users\Lila>

Related articles:

  1. WMIC Share Get

  2. Determining S.M.A.R.T disk drive status from a command prompt

  3. Show all drives from Windows command prompt

References:

  1. Check for Daylight Savings Time by Using PowerShell
    By:
    The Scripting Guys
    Date: October 23, 2012

    Hey, Scripting Guy! Blog

  1. Using the %DATE% and %TIME% Variables

  2. Formatting Date and Time

  3. Combining Date and Time

  4. Conclusion

  5. FAQ

How to Get the Date and Time in Batch Script

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

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как обновить skype на windows 10
  • Оптимизация запуска windows 10
  • Wmasf dll windows xp
  • Что нужно сохранить перед переустановкой windows 10
  • Take ownership windows 10 download