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» для смены кодировки, в противном случае русский текст будет превращен в непонятные символы.
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:
-
WMIC Share Get
-
Determining S.M.A.R.T disk drive status from a command prompt
-
Show all drives from Windows command prompt
References:
-
Check for Daylight Savings Time by Using PowerShell
By:
The Scripting Guys
Date: October 23, 2012Hey, Scripting Guy! Blog
Display or set the system time.
Syntax TIME [new_time] TIME TIME /T key new_time : The time as HH:MM
TIME with no parameters will display the current time and prompt for a new value.
Pressing ENTER will keep the same time.
/T : Just display the time, formatted according to the current Regional settings.
Time Formatting
In Control Panel, Regional settings a Time Appearance can be set. This can be used to change the separator, and the number of characters used to display hours and minutes.
To display the time including Seconds and Hundredths of a second:
ECHO:| TIME
The time Separator, Country Code and Time format can be read from the registry using REG as follows:
@Echo off FOR /F "TOKENS=3" %%D IN ('REG QUERY ^"HKEY_CURRENT_USER\Control Panel\International^" /v iCountry ^| find ^"REG_SZ^"') DO ( SET _country_code=%%D) Echo Country Code %_country_code% FOR /F "TOKENS=3" %%D IN ('REG QUERY ^"HKEY_CURRENT_USER\Control Panel\International^" /v sTime ^| find ^"REG_SZ^"') DO ( SET _time_sep=%%D) Echo Separator %_time_sep% FOR /F "TOKENS=3" %%D IN ('REG QUERY ^"HKEY_CURRENT_USER\Control Panel\International^" /v sTimeFormat ^| find ^"REG_SZ^"') DO ( SET _time_format=%%D) Echo Format %_time_format%
Country Codes/Formats
The default time formats for different country codes are below.
Thses values are user changeable so it is not safe to assue the default will be correct for any particular user.
Country/language Date format Time format Country Code United States MM/dd/yyyy H:mm:ss.tt 001 Czechoslovakia dd.MM.yyyy HH:mm:ss 042 France dd.MM.yyyy HH:mm:ss 033 Germany dd.MM.yyyy HH:mm:ss 049 Latin America dd/MM/yyyy H:mm:ss.tt 003 Intl. English dd/MM/yyyy HH:mm:ss.tt 061 Portugal dd-MM-yyyy HH:mm:ss 351 Finland d.M.yyyy HH.mm.ss 358 Switzerland dd.MM.yy HH mm.ss 041 Norway dd.MM.yy HH:mm:ss 047 Belgium dd/MM/yy HH:mm:ss 032 Brazil dd/MM/yy HH:mm:ss 055 Italy dd/MM/yy HH.mm.ss 039 United Kingdom dd/MM/yy HH:mm:ss 044 Denmark dd-MM-yy HH.mm.ss 045 Netherlands dd-MM-yy HH:mm:ss 031 Spain d/MM/yy HH:mm:ss 034 Hungary yyyy.MM.dd HH:mm:ss 036 Canadian-French yyyy-MM-dd HH:mm:ss 002 Poland yyyy-MM-dd HH:mm:ss 048 Sweden yyyy-MM-dd HH.mm.ss 046 yyyy = 4 digit year yy = 2 digit year dd = 2 digit day d = 1/2 digit day HH = 2 digit Hour H = 1/2 digit hour mm = 2 digit minutes ss = 2 digit seconds tt = AM/PM indicator t = a/p indicator
Errorlevels
If the time was successfully changed (or not given) %ERRORLEVEL% = 0
If it fails, e.g. the user lacks the privilege %ERRORLEVEL% = 1
TIME is an internal command. If Command Extensions are disabled TIME will not support the /T switch
Here is how to quickly check the current date and time from Windows command prompt :
1. Open Windows command prompt (Click on Windows orb and type “cmd” in the search box).
2. Type :
The same can be done by simply typing “date” and “time” but the display will prompt one to enter a new date and time if needed, hitting Enter would skip the process.
Cheers.
Related Post