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
The following sample batch script 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?
Moreover, 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
To print today’s date on the command prompt, we can run date /t . 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.