How do I get current datetime on the Windows command line, in a suitable format for using in a filename?
Update: Now that it's 2016 I'd use PowerShell for this unless there's a really compelling backwards-compatible reason for it, particularly because of the regional settings issue with using date
. See @npocmaka's https://stackoverflow.com/a/19799236/8479
What's a Windows command line statement(s) I can use to get the current datetime in a format that I can put into a filename?
I want to have a .bat file that zips up a directory into an archive with the current date and time as part of the name, for example, Code_2008-10-14_2257.zip
. Is there any easy way I can do this, independent of the regional settings of the machine?
I don't really mind about the date format, ideally it'd be yyyy-mm-dd, but anything simple is fine.
So far I've got this, which on my machine gives me Tue_10_14_2008_230050_91
:
rem Get the datetime in a format that can go in a filename.
set _my_datetime=%date%_%time%
set _my_datetime=%_my_datetime: =_%
set _my_datetime=%_my_datetime::=%
set _my_datetime=%_my_datetime:/=_%
set _my_datetime=%_my_datetime:.=_%
rem Now use the timestamp by in a new ZIP file name.
"d:Program Files7-Zip7z.exe" a -r Code_%_my_datetime%.zip Code
I can live with this, but it seems a bit clunky. Ideally it'd be briefer and have the format mentioned earlier.
I'm using Windows Server 2003 and Windows XP Professional. I don't want to install additional utilities to achieve this (although I realise there are some that will do nice date formatting).
windows datetime command-line batch-file
add a comment |
Update: Now that it's 2016 I'd use PowerShell for this unless there's a really compelling backwards-compatible reason for it, particularly because of the regional settings issue with using date
. See @npocmaka's https://stackoverflow.com/a/19799236/8479
What's a Windows command line statement(s) I can use to get the current datetime in a format that I can put into a filename?
I want to have a .bat file that zips up a directory into an archive with the current date and time as part of the name, for example, Code_2008-10-14_2257.zip
. Is there any easy way I can do this, independent of the regional settings of the machine?
I don't really mind about the date format, ideally it'd be yyyy-mm-dd, but anything simple is fine.
So far I've got this, which on my machine gives me Tue_10_14_2008_230050_91
:
rem Get the datetime in a format that can go in a filename.
set _my_datetime=%date%_%time%
set _my_datetime=%_my_datetime: =_%
set _my_datetime=%_my_datetime::=%
set _my_datetime=%_my_datetime:/=_%
set _my_datetime=%_my_datetime:.=_%
rem Now use the timestamp by in a new ZIP file name.
"d:Program Files7-Zip7z.exe" a -r Code_%_my_datetime%.zip Code
I can live with this, but it seems a bit clunky. Ideally it'd be briefer and have the format mentioned earlier.
I'm using Windows Server 2003 and Windows XP Professional. I don't want to install additional utilities to achieve this (although I realise there are some that will do nice date formatting).
windows datetime command-line batch-file
4
Creating an automated backup for your code? Good for you! We should do this too :)
– Andrei Rînea
Apr 14 '10 at 16:09
18
use powershell people...[datetime]::now.tostring("yyyy-MM-dd")
– Nacht
Oct 29 '14 at 0:03
Is it possible to load files with created date using xp_cmdshell in SQL Server ? I have asked a question on stackoverflow, please kindly see the link @ stackoverflow.com/q/32293517/3327081
– kolunar
Sep 2 '15 at 13:14
add a comment |
Update: Now that it's 2016 I'd use PowerShell for this unless there's a really compelling backwards-compatible reason for it, particularly because of the regional settings issue with using date
. See @npocmaka's https://stackoverflow.com/a/19799236/8479
What's a Windows command line statement(s) I can use to get the current datetime in a format that I can put into a filename?
I want to have a .bat file that zips up a directory into an archive with the current date and time as part of the name, for example, Code_2008-10-14_2257.zip
. Is there any easy way I can do this, independent of the regional settings of the machine?
I don't really mind about the date format, ideally it'd be yyyy-mm-dd, but anything simple is fine.
So far I've got this, which on my machine gives me Tue_10_14_2008_230050_91
:
rem Get the datetime in a format that can go in a filename.
set _my_datetime=%date%_%time%
set _my_datetime=%_my_datetime: =_%
set _my_datetime=%_my_datetime::=%
set _my_datetime=%_my_datetime:/=_%
set _my_datetime=%_my_datetime:.=_%
rem Now use the timestamp by in a new ZIP file name.
"d:Program Files7-Zip7z.exe" a -r Code_%_my_datetime%.zip Code
I can live with this, but it seems a bit clunky. Ideally it'd be briefer and have the format mentioned earlier.
I'm using Windows Server 2003 and Windows XP Professional. I don't want to install additional utilities to achieve this (although I realise there are some that will do nice date formatting).
windows datetime command-line batch-file
Update: Now that it's 2016 I'd use PowerShell for this unless there's a really compelling backwards-compatible reason for it, particularly because of the regional settings issue with using date
. See @npocmaka's https://stackoverflow.com/a/19799236/8479
What's a Windows command line statement(s) I can use to get the current datetime in a format that I can put into a filename?
I want to have a .bat file that zips up a directory into an archive with the current date and time as part of the name, for example, Code_2008-10-14_2257.zip
. Is there any easy way I can do this, independent of the regional settings of the machine?
I don't really mind about the date format, ideally it'd be yyyy-mm-dd, but anything simple is fine.
So far I've got this, which on my machine gives me Tue_10_14_2008_230050_91
:
rem Get the datetime in a format that can go in a filename.
set _my_datetime=%date%_%time%
set _my_datetime=%_my_datetime: =_%
set _my_datetime=%_my_datetime::=%
set _my_datetime=%_my_datetime:/=_%
set _my_datetime=%_my_datetime:.=_%
rem Now use the timestamp by in a new ZIP file name.
"d:Program Files7-Zip7z.exe" a -r Code_%_my_datetime%.zip Code
I can live with this, but it seems a bit clunky. Ideally it'd be briefer and have the format mentioned earlier.
I'm using Windows Server 2003 and Windows XP Professional. I don't want to install additional utilities to achieve this (although I realise there are some that will do nice date formatting).
windows datetime command-line batch-file
windows datetime command-line batch-file
edited Jul 15 '17 at 11:37
Peter Mortensen
13.4k1983111
13.4k1983111
asked Oct 14 '08 at 22:25
Rory
24.7k40136210
24.7k40136210
4
Creating an automated backup for your code? Good for you! We should do this too :)
– Andrei Rînea
Apr 14 '10 at 16:09
18
use powershell people...[datetime]::now.tostring("yyyy-MM-dd")
– Nacht
Oct 29 '14 at 0:03
Is it possible to load files with created date using xp_cmdshell in SQL Server ? I have asked a question on stackoverflow, please kindly see the link @ stackoverflow.com/q/32293517/3327081
– kolunar
Sep 2 '15 at 13:14
add a comment |
4
Creating an automated backup for your code? Good for you! We should do this too :)
– Andrei Rînea
Apr 14 '10 at 16:09
18
use powershell people...[datetime]::now.tostring("yyyy-MM-dd")
– Nacht
Oct 29 '14 at 0:03
Is it possible to load files with created date using xp_cmdshell in SQL Server ? I have asked a question on stackoverflow, please kindly see the link @ stackoverflow.com/q/32293517/3327081
– kolunar
Sep 2 '15 at 13:14
4
4
Creating an automated backup for your code? Good for you! We should do this too :)
– Andrei Rînea
Apr 14 '10 at 16:09
Creating an automated backup for your code? Good for you! We should do this too :)
– Andrei Rînea
Apr 14 '10 at 16:09
18
18
use powershell people...
[datetime]::now.tostring("yyyy-MM-dd")
– Nacht
Oct 29 '14 at 0:03
use powershell people...
[datetime]::now.tostring("yyyy-MM-dd")
– Nacht
Oct 29 '14 at 0:03
Is it possible to load files with created date using xp_cmdshell in SQL Server ? I have asked a question on stackoverflow, please kindly see the link @ stackoverflow.com/q/32293517/3327081
– kolunar
Sep 2 '15 at 13:14
Is it possible to load files with created date using xp_cmdshell in SQL Server ? I have asked a question on stackoverflow, please kindly see the link @ stackoverflow.com/q/32293517/3327081
– kolunar
Sep 2 '15 at 13:14
add a comment |
27 Answers
27
active
oldest
votes
See Windows Batch File (.bat) to get current date in MMDDYYYY format:
@echo off
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ('time /t') do (set mytime=%%a%%b)
echo %mydate%_%mytime%
If you prefer the time in 24 hour/military format, you can replace the second FOR line with this:
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)
C:> .date.bat
2008-10-14_0642
If you want the date independently of the region day/month order, you can use "WMIC os GET LocalDateTime" as a source, since it's in ISO order:
@echo off
for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j
set ldt=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% %ldt:~8,2%:%ldt:~10,2%:%ldt:~12,6%
echo Local date is [%ldt%]
C:>test.cmd
Local date is [2012-06-19 10:23:47.048]
4
This is good! On my system 'time /t' gives '11:58 PM'. I could add another line with "set mytime=%mytime: =_%", or any other tweaks you can suggest?
– Rory
Oct 14 '08 at 22:58
40
For UK folks you'll wantFor /f "tokens=1-3 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%b-%%a)
for the second line.
– Rory
Jan 13 '11 at 18:24
15
This solution is locale dependent, Rory gave the example for UK for other locales where the date comes as 22-02-2012 you need to replace delims=/ with delims=-
– Nuno Furtado
Feb 28 '12 at 21:59
19
On my system %TIME% returns values like " 0:01:15" and " 3:15:12" and the %%a%%b code in the answer gives a leading space like " 001" and " 315". To get a four digit hhmm use this:For /f "tokens=1-2 delims=/: " %%a in ("%TIME%") do (if %%a LSS 10 (set mytime=0%%a%%b) else (set mytime=%%a%%b))
That returns values like "0001" and "0315" which I prefer in my filenames.
– twamley
May 16 '12 at 17:20
9
Nice version of thewmic
command! So far I've only seenWMIC Path Win32_LocalTime Get Day,Hour,Minute,Month,Second,Year /Format:table
. Likewise, to get20120623-1619
in my local Amsterdam time zone, in one line:for /f %%a in ('wmic os get LocalDateTime ^| findstr ^[0-9]') do (set ts=%%a) & set datetime=%ts:~0,8%-%ts:~8,4%
– Arjan
Jun 23 '12 at 14:20
|
show 13 more comments
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:Toolsetcdate.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:Toolsetcdate.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:Toolsetcdate.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:Toolsetcdate.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.
4
Much better than the oddly more popular solution above but I had to add /t to avoid the prompt on Windows 8.1
– rainabba
Jan 28 '14 at 16:17
6
Built-in Windows 8.1date.exe
seems to be locale dependent. It returns the date in dd/MM/yyyy on my system, if it were locale-independent I would expect either MM/dd/yyyy or yyyy-MM-dd. I don't think this answer is talking about the built-in date.exe but some third-party version of it.
– SSS
Apr 7 '14 at 2:49
1
it is locale independant if you provide it with the desired format on the command line
– terrinecold
Oct 15 '14 at 23:06
3
Please notice that date.exe (part of UnxUtils) is not the same as the build-in date command. So if you have to add /t the windows date command is executed. If something like date.exe +"%Y-%m-%d" works, you have installed the UnxUtils correctly. :-)
– just.do.it
Dec 16 '14 at 8:30
Is it possible to load files with created date using xp_cmdshell in SQL Server ? I have tried "forfiles" command but to no avail. I have asked a question on stackoverflow, please kindly see the link @ stackoverflow.com/q/32293517/3327081
– kolunar
Sep 2 '15 at 13:18
add a comment |
Two more ways that do not depend on the time settings (both taken from :How get data/time independent from localization:). And both also get the day of the week and none of them requires admin permissions!:
MAKECAB - will work on EVERY Windows system (fast, but creates a small temp file) (the foxidrive script):
@echo off
pushd "%temp%"
makecab /D RptFileName=~.rpt /D InfFileName=~.inf /f nul >nul
for /f "tokens=3-7" %%a in ('find /i "makecab"^<~.rpt') do (
set "current-date=%%e-%%b-%%c"
set "current-time=%%d"
set "weekday=%%a"
)
del ~.*
popd
echo %weekday% %current-date% %current-time%
pause
More information about get-date function.
ROBOCOPY - it's not native command for Windows XP and Windows Server 2003, but it can be downloaded from microsoft site. But is built-in in everything from Windows Vista and above:
@echo off
setlocal
for /f "skip=8 tokens=2,3,4,5,6,7,8 delims=: " %%D in ('robocopy /l * /ns /nc /ndl /nfl /np /njh /XF * /XD *') do (
set "dow=%%D"
set "month=%%E"
set "day=%%F"
set "HH=%%G"
set "MM=%%H"
set "SS=%%I"
set "year=%%J"
)
echo Day of the week: %dow%
echo Day of the month : %day%
echo Month : %month%
echo hour : %HH%
echo minutes : %MM%
echo seconds : %SS%
echo year : %year%
endlocal
And three more ways that uses other Windows script languages. They will give you more flexibility e.g. you can get week of the year, time in milliseconds and so on.
JScript/batch hybrid (need to be saved as
.bat
). JScript is available on every system form NT and above, as a part of Windows Script Host (though can be disabled through the registry it's a rare case):
@if (@X)==(@Y) @end /* ---Harmless hybrid line that begins a JScript comment
@echo off
cscript //E:JScript //nologo "%~f0"
exit /b 0
*------------------------------------------------------------------------------*/
function GetCurrentDate() {
// Today date time which will used to set as default date.
var todayDate = new Date();
todayDate = todayDate.getFullYear() + "-" +
("0" + (todayDate.getMonth() + 1)).slice(-2) + "-" +
("0" + todayDate.getDate()).slice(-2) + " " + ("0" + todayDate.getHours()).slice(-2) + ":" +
("0" + todayDate.getMinutes()).slice(-2);
return todayDate;
}
WScript.Echo(GetCurrentDate());
VSCRIPT/BATCH hybrid (Is it possible to embed and execute VBScript within a batch file without using a temporary file?) same case as JScript, but hybridization is not so perfect:
:sub echo(str) :end sub
echo off
'>nul 2>&1|| copy /Y %windir%System32doskey.exe %windir%System32'.exe >nul
'& echo current date:
'& cscript /nologo /E:vbscript "%~f0"
'& exit /b
'0 = vbGeneralDate - Default. Returns date: mm/dd/yy and time if specified: hh:mm:ss PM/AM.
'1 = vbLongDate - Returns date: weekday, monthname, year
'2 = vbShortDate - Returns date: mm/dd/yy
'3 = vbLongTime - Returns time: hh:mm:ss PM/AM
'4 = vbShortTime - Return time: hh:mm
WScript.echo Replace(FormatDateTime(Date,1),", ","-")
PowerShell - can be installed on every machine that has .NET - download from Microsoft (v1, v2, v3 (only for Windows 7 and above)). It is installed by default on everything from Windows 7/Windows Server 2008 and above:
C:> powershell get-date -format "{dd-MMM-yyyy HH:mm}"
To use it from a batch file:
for /f "delims=" %%# in ('powershell get-date -format "{dd-MMM-yyyy HH:mm}"') do @set _date=%%#
Self-compiled jscript.net/batch (never seen a Windows machine without .NET, so I think this is a pretty portable):
@if (@X)==(@Y) @end /****** silent line that start JScript comment ******
@echo off
::::::::::::::::::::::::::::::::::::
::: Compile the script ::::
::::::::::::::::::::::::::::::::::::
setlocal
if exist "%~n0.exe" goto :skip_compilation
set "frm=%SystemRoot%Microsoft.NETFramework"
:: Searching the latest installed .NET framework
for /f "tokens=* delims=" %%v in ('dir /b /s /a:d /o:-n "%SystemRoot%Microsoft.NETFrameworkv*"') do (
if exist "%%vjsc.exe" (
rem :: the javascript.net compiler
set "jsc=%%~dpsnfxvjsc.exe"
goto :break_loop
)
)
echo jsc.exe not found && exit /b 0
:break_loop
call %jsc% /nologo /out:"%~n0.exe" "%~dpsfnx0"
::::::::::::::::::::::::::::::::::::
::: End of compilation ::::
::::::::::::::::::::::::::::::::::::
:skip_compilation
"%~n0.exe"
exit /b 0
****** End of JScript comment ******/
import System;
import System.IO;
var dt=DateTime.Now;
Console.WriteLine(dt.ToString("yyyy-MM-dd hh:mm:ss"));
Logman This cannot get the year and day of the week. It's comparatively slow and also creates a temporary file and is based on the time stamps that logman puts on its log files. It will work on everything from Windows XP and above. It probably will be never used by anybody - including me - but is one more way...
@echo off
setlocal
del /q /f %temp%timestampfile_*
Logman.exe stop ts-CPU 1>nul 2>&1
Logman.exe delete ts-CPU 1>nul 2>&1
Logman.exe create counter ts-CPU -sc 2 -v mmddhhmm -max 250 -c "Processor(_Total)%% Processor Time" -o %temp%timestampfile_ >nul
Logman.exe start ts-CPU 1>nul 2>&1
Logman.exe stop ts-CPU >nul 2>&1
Logman.exe delete ts-CPU >nul 2>&1
for /f "tokens=2 delims=_." %%t in ('dir /b %temp%timestampfile_*^&del /q/f %temp%timestampfile_*') do set timestamp=%%t
echo %timestamp%
echo MM: %timestamp:~0,2%
echo dd: %timestamp:~2,2%
echo hh: %timestamp:~4,2%
echo mm: %timestamp:~6,2%
endlocal
exit /b 0
One more way with WMIC which also gives week of the year and the day of the week, but not the milliseconds (for milliseconds check foxidrive's answer):
for /f %%# in ('wMIC Path Win32_LocalTime Get /Format:value') do @for /f %%@ in ("%%#") do @set %%@
echo %day%
echo %DayOfWeek%
echo %hour%
echo %minute%
echo %month%
echo %quarter%
echo %second%
echo %weekinmonth%
echo %year%
Using TYPEPERF with some efforts to be fast and compatible with different language settings and as fast as possible:
@echo off
setlocal
:: Check if Windows is Windows XP and use Windows XP valid counter for UDP performance
::if defined USERDOMAIN_roamingprofile (set "v=v4") else (set "v=")
for /f "tokens=4 delims=. " %%# in ('ver') do if %%# GTR 5 (set "v=v4") else ("v=")
set "mon="
for /f "skip=2 delims=," %%# in ('typeperf "UDP%v%*" -si 0 -sc 1') do (
if not defined mon (
for /f "tokens=1-7 delims=.:/ " %%a in (%%#) do (
set mon=%%a
set date=%%b
set year=%%c
set hour=%%d
set minute=%%e
set sec=%%f
set ms=%%g
)
)
)
echo %year%.%mon%.%date%
echo %hour%:%minute%:%sec%.%ms%
endlocal
MSHTA allows calling JavaScript methods similar to the JScript method demonstrated in #3 above. Bear in mind that JavaScript's Date object properties involving month values are numbered from 0 to 11, not 1 to 12. So a value of 9 means October.
<!-- : Batch portion
@echo off
setlocal
for /f "delims=" %%I in ('mshta "%~f0"') do set "now.%%~I"
rem Display all variables beginning with "now."
set now.
goto :EOF
end batch / begin HTA -->
<script>
resizeTo(0,0)
var fso = new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1),
now = new Date(),
props=['getDate','getDay','getFullYear','getHours','getMilliseconds','getMinutes',
'getMonth','getSeconds','getTime','getTimezoneOffset','getUTCDate','getUTCDay',
'getUTCFullYear','getUTCHours','getUTCMilliseconds','getUTCMinutes','getUTCMonth',
'getUTCSeconds','getYear','toDateString','toGMTString','toLocaleDateString',
'toLocaleTimeString','toString','toTimeString','toUTCString','valueOf'],
output = ;
for (var i in props) {output.push(props[i] + '()=' + now[props[i]]())}
close(fso.Write(output.join('n')));
</script>
1
for powershell C:>for /f %%i in ('powershell get-date -format "{yyyyMMdd_HHmmss}"') do set datetime=%%i C:>echo %datetime%
– Samuel
May 9 '14 at 13:59
1
makecab
: this works by creating a file called~.rpt
, and searching astring
inside it, beginning withmakecab
, which is a line likeMakeCAB Report: Tue Sep 02 22:15:57 2014
. for me this command is not localized it's locale independent. This trick is relying on that. Let's hope it won't ever be, or else beware!
– n611x007
Sep 2 '14 at 20:19
7
I enjoy the opening text "Two more..." followed by 8 solutions.
– Adam Smith
Oct 20 '15 at 21:30
1
What, nomshta
hybrid? :) Mind if I edit your answer and add one? This seems to be the best collection of esoteric solutions, and it seems likemshta
belongs here.
– rojo
Oct 26 '15 at 14:19
1
The accepted solution wouldn't work for me no matter what I tried. Multiple of these solutions worked for me. (Batch and Powershell).
– Brett Wait
May 15 at 15:19
|
show 2 more comments
Here's a variant from alt.msdos.batch.nt that works local-independently.
Put this in a text file, e.g. getDate.cmd
-----------8<------8<------------ snip -- snip ----------8<-------------
:: Works on any NT/2k machine independent of regional date settings
@ECHO off
SETLOCAL ENABLEEXTENSIONS
if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
for /f "tokens=2-4 delims=(-)" %%a in ('echo:^|date') do (
for /f "tokens=%toks% delims=.-/ " %%i in ('date/t') do (
set '%%a'=%%i
set '%%b'=%%j
set '%%c'=%%k))
if %'yy'% LSS 100 set 'yy'=20%'yy'%
set Today=%'yy'%-%'mm'%-%'dd'%
ENDLOCAL & SET v_year=%'yy'%& SET v_month=%'mm'%& SET v_day=%'dd'%
ECHO Today is Year: [%V_Year%] Month: [%V_Month%] Day: [%V_Day%]
:EOF
-----------8<------8<------------ snip -- snip ----------8<-------------
To get the code to work sans error msg's to stderr, I had to add the single quotes arount the variable assignments for %%a, %%b and %%c. My locale (PT) was causing errors at one stage in the looping/parsing where stuff like "set =20" was getting executed. The quotes yield a token (albeit empty) for the left-hand side of the assignment statement.
The downside is the messy locale variable names: 'yy', 'mm' and 'dd'. But hey, who cares!
3
This is perfect and is the simplest and most elegant approach i've seen to date.
– Doug
Dec 14 '11 at 0:25
1
See also Jeroen's enhancements, needed as not all locales use the stringsdd
,mm
andyy
in the output ofecho:^|date
.
– Arjan
Jun 23 '12 at 10:01
1
This should be the accepted answer +1
– Inder Kumar Rathore
Mar 7 '13 at 10:53
add a comment |
I use this (again not region independent (UK))
set bklog=%date:~6,4%-%date:~3,2%-%date:~0,2%_%time:~0,2%%time:~3,2%
See Cmd.exe Environment Variables with Colon and Tilde on this little known but very efficient technique. (A pointer to a Microsoft authoritative reference would be appreciated.)
– DavidRR
Dec 16 '13 at 0:33
Here's Microsoft's Batch File Reference for Windows XP. That reference includes Using batch parameters. Unfortunately, no discussion of the 'slicing' technique.
– DavidRR
Dec 16 '13 at 0:51
This doesn't quite work for me. Maybe it is something to do with regional settings? I get an output of "/15/- 1-We_1009" when running it on Wednesday, October 15, 2014.
– Joel B
Oct 15 '14 at 16:11
add a comment |
Unfortunately this is not immune to regional settings, but it does what you want.
set hour=%time:~0,2%
if "%time:~0,1%"==" " set hour=0%time:~1,1%
set _my_datetime=%date:~10,4%-%date:~4,2%-%date:~7,2%_%hour%%time:~3,2%
Amazing the stuff you can find on Wikipedia.
1
Mark - Found Cmd.exe Environment Variables with Colon and Tilde which describes the variable 'slicing' technique exhibited in your answer. Not finding that info any longer in the Wikipedia article. Would like to find an authoritative reference from Microsoft.
– DavidRR
Dec 16 '13 at 0:41
1
Here's Microsoft's Batch File Reference for Windows XP. That reference includes Using batch parameters. Unfortunately, no discussion of the 'slicing' technique.
– DavidRR
Dec 16 '13 at 0:50
add a comment |
Please use the following script to get the current day in the command line:
echo %Date:~0,3%day
6
Played a bit around with this, it is the shortest I found to get Date and Time: echo %date% %time%
– loomi
Nov 23 '12 at 8:49
4
I gotThuday
.
– NReilingh
Dec 5 '13 at 17:37
add a comment |
The first four lines of this code will give you reliable YY DD MM YYYY HH Min Sec variables in Windows XP Professional and higher.
@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"
set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%" & set "fullstamp=%YYYY%-%MM%-%DD%_%HH%%Min%-%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause
add a comment |
Another way (credit):
@For /F "tokens=2,3,4 delims=/ " %%A in ('Date /t') do @(
Set Month=%%A
Set Day=%%B
Set Year=%%C
)
@echo DAY = %Day%
@echo Month = %Month%
@echo Year = %Year%
Note that both my answers here are still reliant on the order of the day and month as determined by regional settings - not sure how to work around that.
add a comment |
"d:Program Files7-Zip7z.exe" a -r code_%date:~10,4%-%date:~4,2%-%date:~7,2%.zip
great.. works as a cake..
– Saravanan
Aug 4 '11 at 3:44
http://www.dotnetperls.com/7-zip-examples
has some good points may be useful for some one in future.
– Saravanan
Aug 4 '11 at 3:47
3
-1 surely this is not independent of date format.
– barlop
Nov 26 '13 at 16:05
add a comment |
This isn't really briefer but might be a more flexible way (credit):
FOR /F "TOKENS=1* DELIMS= " %%A IN ('DATE/T') DO SET CDATE=%%B
FOR /F "TOKENS=1,2 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET mm=%%B
FOR /F "TOKENS=1,2 DELIMS=/ eol=/" %%A IN ('echo %CDATE%') DO SET dd=%%B
FOR /F "TOKENS=2,3 DELIMS=/ " %%A IN ('echo %CDATE%') DO SET yyyy=%%B
SET date=%mm%%dd%%yyyy%
add a comment |
Here's a way to get date time in a single line:
for /f "tokens=2,3,4,5,6 usebackq delims=:/ " %a in ('%date% %time%') do echo %c-%a-%b %d%e
In the US this will output "yyyy-mm-dd hhmm". Different regional settings will result in different %date% outputs, but you can modify the token order.
If you want a different format, modify the echo statement by rearranging the tokens or using different (or no) separators.
add a comment |
Just use this line:
PowerShell -Command "get-date"
add a comment |
Short answer :
:: Start - Run , type:
cmd /c "powershell get-date -format ^"{yyyy-MM-dd HH:mm:ss}^"|clip"
:: click into target media, Ctrl + V to paste the result
Long answer
@echo off
:: START USAGE ==================================================================
::SET THE NICETIME
:: SET NICETIME=BOO
:: CALL GetNiceTime.cmd
:: ECHO NICETIME IS %NICETIME%
:: echo nice time is %NICETIME%
:: END USAGE ==================================================================
echo set hhmmsss
:: this is Regional settings dependant so tweak this according your current settings
for /f "tokens=1-3 delims=:" %%a in ('echo %time%') do set hhmmsss=%%a%%b%%c
::DEBUG ECHO hhmmsss IS %hhmmsss%
::DEBUG PAUSE
echo %yyyymmdd%
:: this is Regional settings dependant so tweak this according your current settings
for /f "tokens=1-3 delims=." %%D in ('echo %DATE%') do set yyyymmdd=%%F%%E%%D
::DEBUG ECHO yyyymmdd IS %yyyymmdd%
::DEBUG PAUSE
set NICETIME=%yyyymmdd%_%hhmmsss%
::DEBUG echo THE NICETIME IS %NICETIME%
::DEBUG PAUSE
:: in cmd for /f %i in ('PowerShell -Command "get-date" -format "yyyyMMdd"') do set yyyyMMdd=%i ::in cmd script for /f %%i in ('PowerShell -Command "get-date" -format "yyyyMMdd"') do set yyyyMMdd=%%i
– Yordan Georgiev
Dec 19 '16 at 14:09
add a comment |
And here is a similar batch-file for the time portion.
:: http://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi
:: Works on any NT/2k machine independent of regional time settings
::
:: Gets the time in ISO 8601 24-hour format
::
:: Note that %time% gets you fractions of seconds, and time /t doesn't, but gets you AM/PM if your locale supports that.
:: Since ISO 8601 does not care about AM/PM, we use %time%
::
@ECHO off
SETLOCAL ENABLEEXTENSIONS
for /f "tokens=1-4 delims=:,.-/ " %%i in ('echo %time%') do (
set 'hh'=%%i
set 'mm'=%%j
set 'ss'=%%k
set 'ff'=%%l)
ENDLOCAL & SET v_Hour=%'hh'%& SET v_Minute=%'mm'%& SET v_Second=%'ss'%& SET v_Fraction=%'ff'%
ECHO Now is Hour: [%V_Hour%] Minute: [%V_Minute%] Second: [%v_Second%] Fraction: [%v_Fraction%]
set timestring=%V_Hour%%V_Minute%%v_Second%.%v_Fraction%
echo %timestring%
:EOF
--jeroen
Hi, I was able to load files according to Modified date using a command below,z: & forfiles /m *.jpg /s /d 07/16/2015 /c “cmd /c echo @fdate @ftime @path”
But I wanna know how to load files according to Created date. Any help would be very appreciated. A question’s been asked on stackoverflow but no answer yet. Please take a look at the link for the details stackoverflow.com/q/32293517/3327081
– kolunar
Sep 2 '15 at 13:35
1
Ask a new question about that. I've never usedforfiles
.
– Jeroen Wiert Pluimers
Sep 4 '15 at 11:09
add a comment |
I changed the answer with the batch file from vMax so it works with the Dutch language too.
The Dutch - persistent as we are - have a few changes in the %date%
, date/t
, and date
that break the original batch-file.
It would be nice if some people can check this against other Windows locales as well, and report back the results.
If the batch-file fails at your location, then please include the output of these two statements on the command prompt:echo:^|date
date/t
This is a sample of the output you should get from the batch-file:
C:temp>set-date-cmd.bat
Today is Year: [2011] Month: [01] Day: [03]
20110103
Here is the revised code with comments on why:
:: https://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi
:: Works on any NT/2k machine independent of regional date settings
::
:: 20110103 - adapted by jeroen@pluimers.com for Dutch locale
:: Dutch will get jj as year from echo:^|date, so the '%%c' trick does not work as it will fill 'jj', but we want 'yy'
:: luckily, all countries seem to have year at the end: http://en.wikipedia.org/wiki/Calendar_date
:: set '%%c'=%%k
:: set 'yy'=%%k
::
:: In addition, date will display the current date before the input prompt using dashes
:: in Dutch, but using slashes in English, so there will be two occurances of the outer loop in Dutch
:: and one occurence in English.
:: This skips the first iteration:
:: if "%%a" GEQ "A"
::
:: echo:^|date
:: Huidige datum: ma 03-01-2011
:: Voer de nieuwe datum in: (dd-mm-jj)
:: The current date is: Mon 01/03/2011
:: Enter the new date: (mm-dd-yy)
::
:: date/t
:: ma 03-01-2011
:: Mon 01/03/2011
::
:: The assumption in this batch-file is that echo:^|date will return the date format
:: using either mm and dd or dd and mm in the first two valid tokens on the second line, and the year as the last token.
::
:: The outer loop will get the right tokens, the inner loop assigns the variables depending on the tokens.
:: That will resolve the order of the tokens.
::
@ECHO off
set v_day=
set v_month=
set v_year=
SETLOCAL ENABLEEXTENSIONS
if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
::DEBUG echo toks=%toks%
for /f "tokens=2-4 delims=(-)" %%a in ('echo:^|date') do (
::DEBUG echo first token=%%a
if "%%a" GEQ "A" (
for /f "tokens=%toks% delims=.-/ " %%i in ('date/t') do (
set '%%a'=%%i
set '%%b'=%%j
set 'yy'=%%k
)
)
)
if %'yy'% LSS 100 set 'yy'=20%'yy'%
set Today=%'yy'%-%'mm'%-%'dd'%
ENDLOCAL & SET v_year=%'yy'%& SET v_month=%'mm'%& SET v_day=%'dd'%
ECHO Today is Year: [%V_Year%] Month: [%V_Month%] Day: [%V_Day%]
set datestring=%V_Year%%V_Month%%V_Day%
echo %datestring%
:EOF
--jeroen
2
Some do use years first, or lack leading zeroes; see Wikipedia's Date format by country. The French might usejj-mm-aaaa
for jour, mois, annee? Italians maybegg/mm/aaaa
for giorno, mese, anno? Germanstt.mm.jjjj
for Tag, Monat, Jahr? But then: I guess in most countries only a few languages are used. Like in The Netherlands indeed Windows will often be English or Dutch, not much else. Good enough for me.
– Arjan
Jun 23 '12 at 9:49
2
As an aside: another version in Hidden features of Windows batch files is less perfect (needs the fix for the Dutchjj
, and does not enforce a 4 digit year), but usesshift
to discard the day likeMon
orma
. Just different.
– Arjan
Jun 23 '12 at 9:50
3
It breaks on a German system. Year and month work, but day fails because "day" starts with a "T" in German ("Tag"), not a "d". The format string in the prompt is(TT-MM-JJ)
, thedate/t
output is23.06.2012
. /cc @Arjan
– balpha♦
Jun 23 '12 at 10:18
2
Another aside: one could also get the order from the registry, usingreg query "HKCUControl PanelInternational" /vShortDate
. Beware while testing: for an open command prompt, changing that Control Panel setting also changes the format used to display the date (for bothdate
anddate /t
andecho %date%
), but on Windows 7 does NOT change the format for the new date! Like changing my short date format intoYY/MM/dd
, gets me:The current date is: 12/06/23 Enter the new date: (mm-dd-yy)
. Opening a new command prompt fixes that.
– Arjan
Jun 23 '12 at 10:38
2
@Arjan this should bereg query "HKCUControl PanelInternational" /v sShortDate
.
– tricasse
Nov 19 '15 at 13:31
|
show 2 more comments
Matthew Johnson's one-liner solution to get the one-liner date and time is eloquent and useful.
It does however need a simple modification to work from within a batch file:
for /f "tokens=2,3,4,5,6 usebackq delims=:/ " %%a in ('%date% %time%') do echo %%c-%%a-%%b %%d%%e
Does not work in CMD (%%a was unexpected at this time) or in PowerShell (Missing opening '(' after keyword for) on Windows 8.1
– rainabba
Jan 28 '14 at 16:28
3
Rainabba, that is exactly the error you get when that command is issued from the CMD line. However, "from within a batch file", the command returns "2014-01-30 1324".
– John Langstaff
Jan 30 '14 at 18:30
add a comment |
A function that is based on wmic
:
:Now -- Gets the current date and time into separate variables
:: %~1: [out] Year
:: %~2: [out] Month
:: %~3: [out] Day
:: %~4: [out] Hour
:: %~5: [out] Minute
:: %~6: [out] Second
setlocal
for /f %%t in ('wmic os get LocalDateTime ^| findstr /b [0-9]') do set T=%%t
endlocal & (
if "%~1" neq "" set %~1=%T:~0,4%
if "%~2" neq "" set %~2=%T:~4,2%
if "%~3" neq "" set %~3=%T:~6,2%
if "%~4" neq "" set %~4=%T:~8,2%
if "%~5" neq "" set %~5=%T:~10,2%
if "%~6" neq "" set %~6=%T:~12,2%
)
goto:eof
Upside: Region independent. Downside: Only system administrators can run wmic.exe.
Usage:
call:Now Y M D H N S
echo %Y%-%M%-%D% %H%:%N%:%S%
This echos a string like this:
2014-01-22 12:51:53
Note that function parameters are out-Parameters - that is, you must supply variable names instead of values.
All parameters are optional, so call:Now Y M
is a valid call if you only want to get year and month.
add a comment |
This is what I've used:
::Date Variables - replace characters that are not legal as part of filesystem file names (to produce name like "backup_04.15.08.7z")
SET DT=%date%
SET DT=%DT:/=.%
SET DT=%DT:-=.%
If you want further ideas for automating backups to 7-Zip archives, I have a free/open project you can use or review for ideas: http://wittman.org/ziparcy/
On my system %date% contains "Tue 10/14/2008". So, you'll still need to cut off (or otherwise deal with) the "Tue" and the space character.
– BoltBait
Oct 14 '08 at 22:34
Hi @micahwittman. Is it possible to load files with created date using xp_cmdshell in SQL Server ? I have tried "forfiles" command but to no avail. I have asked a question on stackoverflow, please kindly see the link @ stackoverflow.com/q/32293517/3327081
– kolunar
Sep 2 '15 at 13:17
add a comment |
I had a similar problem. I have an automatic daily download from an FTP server of an encrypted file. I wanted to decrypt the file using gpg, rename the file to the current date (YYYYMMDD format) and drop the decrypted file into a folder for the correct department.
I went through several suggestions for renaming the file according to date and was having no luck until I stumbled upon this simple solution.
for /f "tokens=1-5 delims=/ " %%d in ("%date%") do rename "decrypted.txt" %%g-%%e-%%f.txt
It worked perfectly (i.e., the filename comes out as "2011-06-14.txt").
(Source)
add a comment |
http://sourceforge.net/projects/unxutils/files/
Look inside the ZIP file for something called "Date.exe" and rename it "DateFormat.exe" (to avoid conflicts).
Put it in your Windows system32 folder.
It has a lot of "date output" options.
For help, use DateFormat.exe --h
I'm not sure how you would put its output into an environment variable... using SET.
1
Thanks, although this question is specifically for doing it without downloading additional tools.
– Rory
Oct 31 '10 at 12:22
add a comment |
Regional independent solution generating the ISO date format:
rem save the existing format definition
for /f "skip=2 tokens=3" %%a in ('reg query "HKCUControl PanelInternational" /v sShortDate') do set FORMAT=%%a
rem set ISO specific format definition
reg add "HKCUControl PanelInternational" /v sShortDate /t REG_SZ /f /d yyyy-MM-dd 1>nul:
rem query the date in the ISO specific format
set ISODATE=%DATE%
rem restore previous format definition
reg add "HKCUControl PanelInternational" /v sShortDate /t REG_SZ /f /d %FORMAT% 1>nul:
What could still be optimized:
Other processes might get confused if using the date format in the short period while it is modified. So parsing the output according to the existing format string could be 'safer' - but will be more complicated
you could reg query iDate (technet.microsoft.com/en-us/library/cc978637.aspx) and conditionally proceed (3 possible values according to technet) - although I have not tried this yet.
– Vincent De Smet
May 5 '12 at 19:08
add a comment |
:: GetDate.cmd -> Uses WMIC.exe to get current date and time in ISO 8601 format
:: - Sets environment variables %_isotime% and %_now% to current time
:: - On failure, clears these environment variables
:: Inspired on -> https://ss64.com/nt/syntax-getdate.html
:: - (cX) 2017 adolfo.dimare@gmail.com
:: - http://stackoverflow.com/questions/203090
@echo off
set _isotime=
set _now=
:: Check that WMIC.exe is available
WMIC.exe Alias /? >NUL 2>&1 || goto _WMIC_MISSING_
if not (%1)==() goto _help
SetLocal EnableDelayedExpansion
:: Use WMIC.exe to retrieve date and time
FOR /F "skip=1 tokens=1-6" %%G IN ('WMIC.exe Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
IF "%%~L"=="" goto _WMIC_done_
set _yyyy=%%L
set _mm=00%%J
set _dd=00%%G
set _hour=00%%H
set _minute=00%%I
set _second=00%%K
)
:_WMIC_done_
:: 1 2 3 4 5 6
:: %%G %%H %%I %%J %%K %%L
:: Day Hour Minute Month Second Year
:: 27 9 35 4 38 2017
:: Remove excess leading zeroes
set _mm=%_mm:~-2%
set _dd=%_dd:~-2%
set _hour=%_hour:~-2%
set _minute=%_minute:~-2%
set _second=%_second:~-2%
:: Syntax -> %variable:~num_chars_to_skip,num_chars_to_keep%
:: Set date/time in ISO 8601 format:
Set _isotime=%_yyyy%-%_mm%-%_dd%T%_hour%:%_minute%:%_second%
:: -> http://google.com/search?num=100&q=ISO+8601+format
if 1%_hour% LSS 112 set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%am
if 1%_hour% LSS 112 goto _skip_12_
set /a _hour=1%_hour%-12
set _hour=%_hour:~-2%
set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%pm
:: -> https://ss64.com/nt/if.html
:: -> http://google.com/search?num=100&q=SetLocal+EndLocal+Windows
:: 'if () else ()' will NOT set %_now% correctly !?
:_skip_12_
EndLocal & set _isotime=%_isotime% & set _now=%_now%
goto _out
:_WMIC_MISSING_
echo.
echo WMIC.exe command not available
echo - WMIC.exe needs Administrator privileges to run in Windows
echo - Usually the path to WMIC.exe is "%windir%System32wbemWMIC.exe"
:_help
echo.
echo GetDate.cmd: Uses WMIC.exe to get current date and time in ISO 8601 format
echo.
echo %%_now%% environment variable set to current date and time
echo %%_isotime%% environment variable to current time in ISO format
echo set _today=%%_isotime:~0,10%%
echo.
:_out
:: EOF: GetDate.cmd
add a comment |
Given a known locality, for reference in functional form. The ECHOTIMESTAMP
call shows how to get the timestamp into a variable (DTS
in this example.)
@ECHO off
CALL :ECHOTIMESTAMP
GOTO END
:TIMESTAMP
SETLOCAL EnableDelayedExpansion
SET DATESTAMP=!DATE:~10,4!-!DATE:~4,2!-!DATE:~7,2!
SET TIMESTAMP=!TIME:~0,2!-!TIME:~3,2!-!TIME:~6,2!
SET DTS=!DATESTAMP: =0!-!TIMESTAMP: =0!
ENDLOCAL & SET "%~1=%DTS%"
GOTO :EOF
:ECHOTIMESTAMP
SETLOCAL
CALL :TIMESTAMP DTS
ECHO %DTS%
ENDLOCAL
GOTO :EOF
:END
EXIT /b 0
And saved to file, timestamp.bat, here's the output:
It seems that this comes with the regional issue - this doesn't work in all English machines.
– SteveFest
Jul 21 '17 at 1:11
Not surprised, @SteveFest . If it were possible to temporarily set the locale, that might help to provide a global solution, but it seems it's necessary to the know the region in advance. Is your locale en-US or en-SomewhereElse?
– bvj
Jul 21 '17 at 7:01
Mine is zh-HK, with edited date time format
– SteveFest
Jul 21 '17 at 7:02
@SteveFest I suppose it would be possible to build up a list of locales where each includes date/time expressions with a sample to validate. I'm super busy, but I'll try to update my answer to illustrate. Could you show me samples of the HK time/date outputs? I may be foolishly assuming zh-HK prints digits at fixed offsets.
– bvj
Jul 23 '17 at 4:10
zh-HK:(yy)yy年m月d日 hh:mm
- no leading zeros. (yy) could be ignore as we have 2 digit year, or 4 digit year. But please note one thing: the date time format can be changed per machine.
– SteveFest
Jul 23 '17 at 4:42
|
show 4 more comments
With Windows 7, this code works for me:
SET DATE=%date%
SET YEAR=%DATE:~0,4%
SET MONTH=%DATE:~5,2%
SET DAY=%DATE:~8,2%
ECHO %YEAR%
ECHO %MONTH%
ECHO %DAY%
SET DATE_FRM=%YEAR%-%MONTH%-%DAY%
ECHO %DATE_FRM%
And again. It's nice that it works on your machine, but you missed the pointindependent of the regional settings of the machine
– jeb
Aug 16 '16 at 11:06
Ok, but others example don't work at all for me
– Frizz1977
Aug 16 '16 at 11:30
add a comment |
I know that there are numerous ways mentioned already. But here is my way to break it down to understand how it is done. Hopefully, it is helpful for someone who like step by step method.
:: Check your local date format
echo %date%
:: Output is Mon 08/15/2016
:: get day (start index, number of characters)
:: (index starts with zero)
set myday=%DATE:~0,4%
echo %myday%
:: output is Mon
:: get month
set mymonth=%DATE:~4,2%
echo %mymonth%
:: output is 08
:: get date
set mydate=%DATE:~7,2%
echo %mydate%
:: output is 15
:: get year
set myyear=%DATE:~10,4%
echo %myyear%
:: output is 2016
3
You missed the pointindependent of the regional settings of the machine
– jeb
Aug 15 '16 at 16:13
add a comment |
I note that the o/p did not ask for a region-independent solution. My solution is for the UK though.
This is the simplest possible solution, a 1-line solution, for use in a Batch file:
FOR /F "tokens=1-3 delims=/" %%A IN ("%date%") DO (SET today=%%C-%%B-%%A)
echo %today%
2
He mentioned a region independent solution...particularly because of the regional settings issue with using date
. Btw. Your solution is the same as the twenty other answers.
– jeb
Dec 6 at 10:57
Yeah, but mine actually could (optionally) be used on the command line. What is the merit in posting 35 lines of code, if one line of code will provide the same solution?
– Ed999
Dec 6 at 18:37
I can't see any relevant difference to the old answers of @Matthew Johnson, 2010 or @KChiki, 2011
– jeb
Dec 7 at 7:27
add a comment |
protected by Community♦ Apr 9 '12 at 8:44
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
27 Answers
27
active
oldest
votes
27 Answers
27
active
oldest
votes
active
oldest
votes
active
oldest
votes
See Windows Batch File (.bat) to get current date in MMDDYYYY format:
@echo off
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ('time /t') do (set mytime=%%a%%b)
echo %mydate%_%mytime%
If you prefer the time in 24 hour/military format, you can replace the second FOR line with this:
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)
C:> .date.bat
2008-10-14_0642
If you want the date independently of the region day/month order, you can use "WMIC os GET LocalDateTime" as a source, since it's in ISO order:
@echo off
for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j
set ldt=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% %ldt:~8,2%:%ldt:~10,2%:%ldt:~12,6%
echo Local date is [%ldt%]
C:>test.cmd
Local date is [2012-06-19 10:23:47.048]
4
This is good! On my system 'time /t' gives '11:58 PM'. I could add another line with "set mytime=%mytime: =_%", or any other tweaks you can suggest?
– Rory
Oct 14 '08 at 22:58
40
For UK folks you'll wantFor /f "tokens=1-3 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%b-%%a)
for the second line.
– Rory
Jan 13 '11 at 18:24
15
This solution is locale dependent, Rory gave the example for UK for other locales where the date comes as 22-02-2012 you need to replace delims=/ with delims=-
– Nuno Furtado
Feb 28 '12 at 21:59
19
On my system %TIME% returns values like " 0:01:15" and " 3:15:12" and the %%a%%b code in the answer gives a leading space like " 001" and " 315". To get a four digit hhmm use this:For /f "tokens=1-2 delims=/: " %%a in ("%TIME%") do (if %%a LSS 10 (set mytime=0%%a%%b) else (set mytime=%%a%%b))
That returns values like "0001" and "0315" which I prefer in my filenames.
– twamley
May 16 '12 at 17:20
9
Nice version of thewmic
command! So far I've only seenWMIC Path Win32_LocalTime Get Day,Hour,Minute,Month,Second,Year /Format:table
. Likewise, to get20120623-1619
in my local Amsterdam time zone, in one line:for /f %%a in ('wmic os get LocalDateTime ^| findstr ^[0-9]') do (set ts=%%a) & set datetime=%ts:~0,8%-%ts:~8,4%
– Arjan
Jun 23 '12 at 14:20
|
show 13 more comments
See Windows Batch File (.bat) to get current date in MMDDYYYY format:
@echo off
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ('time /t') do (set mytime=%%a%%b)
echo %mydate%_%mytime%
If you prefer the time in 24 hour/military format, you can replace the second FOR line with this:
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)
C:> .date.bat
2008-10-14_0642
If you want the date independently of the region day/month order, you can use "WMIC os GET LocalDateTime" as a source, since it's in ISO order:
@echo off
for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j
set ldt=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% %ldt:~8,2%:%ldt:~10,2%:%ldt:~12,6%
echo Local date is [%ldt%]
C:>test.cmd
Local date is [2012-06-19 10:23:47.048]
4
This is good! On my system 'time /t' gives '11:58 PM'. I could add another line with "set mytime=%mytime: =_%", or any other tweaks you can suggest?
– Rory
Oct 14 '08 at 22:58
40
For UK folks you'll wantFor /f "tokens=1-3 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%b-%%a)
for the second line.
– Rory
Jan 13 '11 at 18:24
15
This solution is locale dependent, Rory gave the example for UK for other locales where the date comes as 22-02-2012 you need to replace delims=/ with delims=-
– Nuno Furtado
Feb 28 '12 at 21:59
19
On my system %TIME% returns values like " 0:01:15" and " 3:15:12" and the %%a%%b code in the answer gives a leading space like " 001" and " 315". To get a four digit hhmm use this:For /f "tokens=1-2 delims=/: " %%a in ("%TIME%") do (if %%a LSS 10 (set mytime=0%%a%%b) else (set mytime=%%a%%b))
That returns values like "0001" and "0315" which I prefer in my filenames.
– twamley
May 16 '12 at 17:20
9
Nice version of thewmic
command! So far I've only seenWMIC Path Win32_LocalTime Get Day,Hour,Minute,Month,Second,Year /Format:table
. Likewise, to get20120623-1619
in my local Amsterdam time zone, in one line:for /f %%a in ('wmic os get LocalDateTime ^| findstr ^[0-9]') do (set ts=%%a) & set datetime=%ts:~0,8%-%ts:~8,4%
– Arjan
Jun 23 '12 at 14:20
|
show 13 more comments
See Windows Batch File (.bat) to get current date in MMDDYYYY format:
@echo off
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ('time /t') do (set mytime=%%a%%b)
echo %mydate%_%mytime%
If you prefer the time in 24 hour/military format, you can replace the second FOR line with this:
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)
C:> .date.bat
2008-10-14_0642
If you want the date independently of the region day/month order, you can use "WMIC os GET LocalDateTime" as a source, since it's in ISO order:
@echo off
for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j
set ldt=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% %ldt:~8,2%:%ldt:~10,2%:%ldt:~12,6%
echo Local date is [%ldt%]
C:>test.cmd
Local date is [2012-06-19 10:23:47.048]
See Windows Batch File (.bat) to get current date in MMDDYYYY format:
@echo off
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ('time /t') do (set mytime=%%a%%b)
echo %mydate%_%mytime%
If you prefer the time in 24 hour/military format, you can replace the second FOR line with this:
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)
C:> .date.bat
2008-10-14_0642
If you want the date independently of the region day/month order, you can use "WMIC os GET LocalDateTime" as a source, since it's in ISO order:
@echo off
for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j
set ldt=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% %ldt:~8,2%:%ldt:~10,2%:%ldt:~12,6%
echo Local date is [%ldt%]
C:>test.cmd
Local date is [2012-06-19 10:23:47.048]
edited Jul 15 '17 at 11:39
Peter Mortensen
13.4k1983111
13.4k1983111
answered Oct 14 '08 at 22:36
Jay
34.4k115579
34.4k115579
4
This is good! On my system 'time /t' gives '11:58 PM'. I could add another line with "set mytime=%mytime: =_%", or any other tweaks you can suggest?
– Rory
Oct 14 '08 at 22:58
40
For UK folks you'll wantFor /f "tokens=1-3 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%b-%%a)
for the second line.
– Rory
Jan 13 '11 at 18:24
15
This solution is locale dependent, Rory gave the example for UK for other locales where the date comes as 22-02-2012 you need to replace delims=/ with delims=-
– Nuno Furtado
Feb 28 '12 at 21:59
19
On my system %TIME% returns values like " 0:01:15" and " 3:15:12" and the %%a%%b code in the answer gives a leading space like " 001" and " 315". To get a four digit hhmm use this:For /f "tokens=1-2 delims=/: " %%a in ("%TIME%") do (if %%a LSS 10 (set mytime=0%%a%%b) else (set mytime=%%a%%b))
That returns values like "0001" and "0315" which I prefer in my filenames.
– twamley
May 16 '12 at 17:20
9
Nice version of thewmic
command! So far I've only seenWMIC Path Win32_LocalTime Get Day,Hour,Minute,Month,Second,Year /Format:table
. Likewise, to get20120623-1619
in my local Amsterdam time zone, in one line:for /f %%a in ('wmic os get LocalDateTime ^| findstr ^[0-9]') do (set ts=%%a) & set datetime=%ts:~0,8%-%ts:~8,4%
– Arjan
Jun 23 '12 at 14:20
|
show 13 more comments
4
This is good! On my system 'time /t' gives '11:58 PM'. I could add another line with "set mytime=%mytime: =_%", or any other tweaks you can suggest?
– Rory
Oct 14 '08 at 22:58
40
For UK folks you'll wantFor /f "tokens=1-3 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%b-%%a)
for the second line.
– Rory
Jan 13 '11 at 18:24
15
This solution is locale dependent, Rory gave the example for UK for other locales where the date comes as 22-02-2012 you need to replace delims=/ with delims=-
– Nuno Furtado
Feb 28 '12 at 21:59
19
On my system %TIME% returns values like " 0:01:15" and " 3:15:12" and the %%a%%b code in the answer gives a leading space like " 001" and " 315". To get a four digit hhmm use this:For /f "tokens=1-2 delims=/: " %%a in ("%TIME%") do (if %%a LSS 10 (set mytime=0%%a%%b) else (set mytime=%%a%%b))
That returns values like "0001" and "0315" which I prefer in my filenames.
– twamley
May 16 '12 at 17:20
9
Nice version of thewmic
command! So far I've only seenWMIC Path Win32_LocalTime Get Day,Hour,Minute,Month,Second,Year /Format:table
. Likewise, to get20120623-1619
in my local Amsterdam time zone, in one line:for /f %%a in ('wmic os get LocalDateTime ^| findstr ^[0-9]') do (set ts=%%a) & set datetime=%ts:~0,8%-%ts:~8,4%
– Arjan
Jun 23 '12 at 14:20
4
4
This is good! On my system 'time /t' gives '11:58 PM'. I could add another line with "set mytime=%mytime: =_%", or any other tweaks you can suggest?
– Rory
Oct 14 '08 at 22:58
This is good! On my system 'time /t' gives '11:58 PM'. I could add another line with "set mytime=%mytime: =_%", or any other tweaks you can suggest?
– Rory
Oct 14 '08 at 22:58
40
40
For UK folks you'll want
For /f "tokens=1-3 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%b-%%a)
for the second line.– Rory
Jan 13 '11 at 18:24
For UK folks you'll want
For /f "tokens=1-3 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%b-%%a)
for the second line.– Rory
Jan 13 '11 at 18:24
15
15
This solution is locale dependent, Rory gave the example for UK for other locales where the date comes as 22-02-2012 you need to replace delims=/ with delims=-
– Nuno Furtado
Feb 28 '12 at 21:59
This solution is locale dependent, Rory gave the example for UK for other locales where the date comes as 22-02-2012 you need to replace delims=/ with delims=-
– Nuno Furtado
Feb 28 '12 at 21:59
19
19
On my system %TIME% returns values like " 0:01:15" and " 3:15:12" and the %%a%%b code in the answer gives a leading space like " 001" and " 315". To get a four digit hhmm use this:
For /f "tokens=1-2 delims=/: " %%a in ("%TIME%") do (if %%a LSS 10 (set mytime=0%%a%%b) else (set mytime=%%a%%b))
That returns values like "0001" and "0315" which I prefer in my filenames.– twamley
May 16 '12 at 17:20
On my system %TIME% returns values like " 0:01:15" and " 3:15:12" and the %%a%%b code in the answer gives a leading space like " 001" and " 315". To get a four digit hhmm use this:
For /f "tokens=1-2 delims=/: " %%a in ("%TIME%") do (if %%a LSS 10 (set mytime=0%%a%%b) else (set mytime=%%a%%b))
That returns values like "0001" and "0315" which I prefer in my filenames.– twamley
May 16 '12 at 17:20
9
9
Nice version of the
wmic
command! So far I've only seen WMIC Path Win32_LocalTime Get Day,Hour,Minute,Month,Second,Year /Format:table
. Likewise, to get 20120623-1619
in my local Amsterdam time zone, in one line: for /f %%a in ('wmic os get LocalDateTime ^| findstr ^[0-9]') do (set ts=%%a) & set datetime=%ts:~0,8%-%ts:~8,4%
– Arjan
Jun 23 '12 at 14:20
Nice version of the
wmic
command! So far I've only seen WMIC Path Win32_LocalTime Get Day,Hour,Minute,Month,Second,Year /Format:table
. Likewise, to get 20120623-1619
in my local Amsterdam time zone, in one line: for /f %%a in ('wmic os get LocalDateTime ^| findstr ^[0-9]') do (set ts=%%a) & set datetime=%ts:~0,8%-%ts:~8,4%
– Arjan
Jun 23 '12 at 14:20
|
show 13 more comments
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:Toolsetcdate.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:Toolsetcdate.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:Toolsetcdate.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:Toolsetcdate.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.
4
Much better than the oddly more popular solution above but I had to add /t to avoid the prompt on Windows 8.1
– rainabba
Jan 28 '14 at 16:17
6
Built-in Windows 8.1date.exe
seems to be locale dependent. It returns the date in dd/MM/yyyy on my system, if it were locale-independent I would expect either MM/dd/yyyy or yyyy-MM-dd. I don't think this answer is talking about the built-in date.exe but some third-party version of it.
– SSS
Apr 7 '14 at 2:49
1
it is locale independant if you provide it with the desired format on the command line
– terrinecold
Oct 15 '14 at 23:06
3
Please notice that date.exe (part of UnxUtils) is not the same as the build-in date command. So if you have to add /t the windows date command is executed. If something like date.exe +"%Y-%m-%d" works, you have installed the UnxUtils correctly. :-)
– just.do.it
Dec 16 '14 at 8:30
Is it possible to load files with created date using xp_cmdshell in SQL Server ? I have tried "forfiles" command but to no avail. I have asked a question on stackoverflow, please kindly see the link @ stackoverflow.com/q/32293517/3327081
– kolunar
Sep 2 '15 at 13:18
add a comment |
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:Toolsetcdate.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:Toolsetcdate.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:Toolsetcdate.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:Toolsetcdate.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.
4
Much better than the oddly more popular solution above but I had to add /t to avoid the prompt on Windows 8.1
– rainabba
Jan 28 '14 at 16:17
6
Built-in Windows 8.1date.exe
seems to be locale dependent. It returns the date in dd/MM/yyyy on my system, if it were locale-independent I would expect either MM/dd/yyyy or yyyy-MM-dd. I don't think this answer is talking about the built-in date.exe but some third-party version of it.
– SSS
Apr 7 '14 at 2:49
1
it is locale independant if you provide it with the desired format on the command line
– terrinecold
Oct 15 '14 at 23:06
3
Please notice that date.exe (part of UnxUtils) is not the same as the build-in date command. So if you have to add /t the windows date command is executed. If something like date.exe +"%Y-%m-%d" works, you have installed the UnxUtils correctly. :-)
– just.do.it
Dec 16 '14 at 8:30
Is it possible to load files with created date using xp_cmdshell in SQL Server ? I have tried "forfiles" command but to no avail. I have asked a question on stackoverflow, please kindly see the link @ stackoverflow.com/q/32293517/3327081
– kolunar
Sep 2 '15 at 13:18
add a comment |
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:Toolsetcdate.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:Toolsetcdate.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:Toolsetcdate.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:Toolsetcdate.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.
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:Toolsetcdate.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:Toolsetcdate.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:Toolsetcdate.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:Toolsetcdate.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.
edited Dec 1 '12 at 16:05
Peter Mortensen
13.4k1983111
13.4k1983111
answered Dec 23 '09 at 9:40
Uri Liebeskind
95962
95962
4
Much better than the oddly more popular solution above but I had to add /t to avoid the prompt on Windows 8.1
– rainabba
Jan 28 '14 at 16:17
6
Built-in Windows 8.1date.exe
seems to be locale dependent. It returns the date in dd/MM/yyyy on my system, if it were locale-independent I would expect either MM/dd/yyyy or yyyy-MM-dd. I don't think this answer is talking about the built-in date.exe but some third-party version of it.
– SSS
Apr 7 '14 at 2:49
1
it is locale independant if you provide it with the desired format on the command line
– terrinecold
Oct 15 '14 at 23:06
3
Please notice that date.exe (part of UnxUtils) is not the same as the build-in date command. So if you have to add /t the windows date command is executed. If something like date.exe +"%Y-%m-%d" works, you have installed the UnxUtils correctly. :-)
– just.do.it
Dec 16 '14 at 8:30
Is it possible to load files with created date using xp_cmdshell in SQL Server ? I have tried "forfiles" command but to no avail. I have asked a question on stackoverflow, please kindly see the link @ stackoverflow.com/q/32293517/3327081
– kolunar
Sep 2 '15 at 13:18
add a comment |
4
Much better than the oddly more popular solution above but I had to add /t to avoid the prompt on Windows 8.1
– rainabba
Jan 28 '14 at 16:17
6
Built-in Windows 8.1date.exe
seems to be locale dependent. It returns the date in dd/MM/yyyy on my system, if it were locale-independent I would expect either MM/dd/yyyy or yyyy-MM-dd. I don't think this answer is talking about the built-in date.exe but some third-party version of it.
– SSS
Apr 7 '14 at 2:49
1
it is locale independant if you provide it with the desired format on the command line
– terrinecold
Oct 15 '14 at 23:06
3
Please notice that date.exe (part of UnxUtils) is not the same as the build-in date command. So if you have to add /t the windows date command is executed. If something like date.exe +"%Y-%m-%d" works, you have installed the UnxUtils correctly. :-)
– just.do.it
Dec 16 '14 at 8:30
Is it possible to load files with created date using xp_cmdshell in SQL Server ? I have tried "forfiles" command but to no avail. I have asked a question on stackoverflow, please kindly see the link @ stackoverflow.com/q/32293517/3327081
– kolunar
Sep 2 '15 at 13:18
4
4
Much better than the oddly more popular solution above but I had to add /t to avoid the prompt on Windows 8.1
– rainabba
Jan 28 '14 at 16:17
Much better than the oddly more popular solution above but I had to add /t to avoid the prompt on Windows 8.1
– rainabba
Jan 28 '14 at 16:17
6
6
Built-in Windows 8.1
date.exe
seems to be locale dependent. It returns the date in dd/MM/yyyy on my system, if it were locale-independent I would expect either MM/dd/yyyy or yyyy-MM-dd. I don't think this answer is talking about the built-in date.exe but some third-party version of it.– SSS
Apr 7 '14 at 2:49
Built-in Windows 8.1
date.exe
seems to be locale dependent. It returns the date in dd/MM/yyyy on my system, if it were locale-independent I would expect either MM/dd/yyyy or yyyy-MM-dd. I don't think this answer is talking about the built-in date.exe but some third-party version of it.– SSS
Apr 7 '14 at 2:49
1
1
it is locale independant if you provide it with the desired format on the command line
– terrinecold
Oct 15 '14 at 23:06
it is locale independant if you provide it with the desired format on the command line
– terrinecold
Oct 15 '14 at 23:06
3
3
Please notice that date.exe (part of UnxUtils) is not the same as the build-in date command. So if you have to add /t the windows date command is executed. If something like date.exe +"%Y-%m-%d" works, you have installed the UnxUtils correctly. :-)
– just.do.it
Dec 16 '14 at 8:30
Please notice that date.exe (part of UnxUtils) is not the same as the build-in date command. So if you have to add /t the windows date command is executed. If something like date.exe +"%Y-%m-%d" works, you have installed the UnxUtils correctly. :-)
– just.do.it
Dec 16 '14 at 8:30
Is it possible to load files with created date using xp_cmdshell in SQL Server ? I have tried "forfiles" command but to no avail. I have asked a question on stackoverflow, please kindly see the link @ stackoverflow.com/q/32293517/3327081
– kolunar
Sep 2 '15 at 13:18
Is it possible to load files with created date using xp_cmdshell in SQL Server ? I have tried "forfiles" command but to no avail. I have asked a question on stackoverflow, please kindly see the link @ stackoverflow.com/q/32293517/3327081
– kolunar
Sep 2 '15 at 13:18
add a comment |
Two more ways that do not depend on the time settings (both taken from :How get data/time independent from localization:). And both also get the day of the week and none of them requires admin permissions!:
MAKECAB - will work on EVERY Windows system (fast, but creates a small temp file) (the foxidrive script):
@echo off
pushd "%temp%"
makecab /D RptFileName=~.rpt /D InfFileName=~.inf /f nul >nul
for /f "tokens=3-7" %%a in ('find /i "makecab"^<~.rpt') do (
set "current-date=%%e-%%b-%%c"
set "current-time=%%d"
set "weekday=%%a"
)
del ~.*
popd
echo %weekday% %current-date% %current-time%
pause
More information about get-date function.
ROBOCOPY - it's not native command for Windows XP and Windows Server 2003, but it can be downloaded from microsoft site. But is built-in in everything from Windows Vista and above:
@echo off
setlocal
for /f "skip=8 tokens=2,3,4,5,6,7,8 delims=: " %%D in ('robocopy /l * /ns /nc /ndl /nfl /np /njh /XF * /XD *') do (
set "dow=%%D"
set "month=%%E"
set "day=%%F"
set "HH=%%G"
set "MM=%%H"
set "SS=%%I"
set "year=%%J"
)
echo Day of the week: %dow%
echo Day of the month : %day%
echo Month : %month%
echo hour : %HH%
echo minutes : %MM%
echo seconds : %SS%
echo year : %year%
endlocal
And three more ways that uses other Windows script languages. They will give you more flexibility e.g. you can get week of the year, time in milliseconds and so on.
JScript/batch hybrid (need to be saved as
.bat
). JScript is available on every system form NT and above, as a part of Windows Script Host (though can be disabled through the registry it's a rare case):
@if (@X)==(@Y) @end /* ---Harmless hybrid line that begins a JScript comment
@echo off
cscript //E:JScript //nologo "%~f0"
exit /b 0
*------------------------------------------------------------------------------*/
function GetCurrentDate() {
// Today date time which will used to set as default date.
var todayDate = new Date();
todayDate = todayDate.getFullYear() + "-" +
("0" + (todayDate.getMonth() + 1)).slice(-2) + "-" +
("0" + todayDate.getDate()).slice(-2) + " " + ("0" + todayDate.getHours()).slice(-2) + ":" +
("0" + todayDate.getMinutes()).slice(-2);
return todayDate;
}
WScript.Echo(GetCurrentDate());
VSCRIPT/BATCH hybrid (Is it possible to embed and execute VBScript within a batch file without using a temporary file?) same case as JScript, but hybridization is not so perfect:
:sub echo(str) :end sub
echo off
'>nul 2>&1|| copy /Y %windir%System32doskey.exe %windir%System32'.exe >nul
'& echo current date:
'& cscript /nologo /E:vbscript "%~f0"
'& exit /b
'0 = vbGeneralDate - Default. Returns date: mm/dd/yy and time if specified: hh:mm:ss PM/AM.
'1 = vbLongDate - Returns date: weekday, monthname, year
'2 = vbShortDate - Returns date: mm/dd/yy
'3 = vbLongTime - Returns time: hh:mm:ss PM/AM
'4 = vbShortTime - Return time: hh:mm
WScript.echo Replace(FormatDateTime(Date,1),", ","-")
PowerShell - can be installed on every machine that has .NET - download from Microsoft (v1, v2, v3 (only for Windows 7 and above)). It is installed by default on everything from Windows 7/Windows Server 2008 and above:
C:> powershell get-date -format "{dd-MMM-yyyy HH:mm}"
To use it from a batch file:
for /f "delims=" %%# in ('powershell get-date -format "{dd-MMM-yyyy HH:mm}"') do @set _date=%%#
Self-compiled jscript.net/batch (never seen a Windows machine without .NET, so I think this is a pretty portable):
@if (@X)==(@Y) @end /****** silent line that start JScript comment ******
@echo off
::::::::::::::::::::::::::::::::::::
::: Compile the script ::::
::::::::::::::::::::::::::::::::::::
setlocal
if exist "%~n0.exe" goto :skip_compilation
set "frm=%SystemRoot%Microsoft.NETFramework"
:: Searching the latest installed .NET framework
for /f "tokens=* delims=" %%v in ('dir /b /s /a:d /o:-n "%SystemRoot%Microsoft.NETFrameworkv*"') do (
if exist "%%vjsc.exe" (
rem :: the javascript.net compiler
set "jsc=%%~dpsnfxvjsc.exe"
goto :break_loop
)
)
echo jsc.exe not found && exit /b 0
:break_loop
call %jsc% /nologo /out:"%~n0.exe" "%~dpsfnx0"
::::::::::::::::::::::::::::::::::::
::: End of compilation ::::
::::::::::::::::::::::::::::::::::::
:skip_compilation
"%~n0.exe"
exit /b 0
****** End of JScript comment ******/
import System;
import System.IO;
var dt=DateTime.Now;
Console.WriteLine(dt.ToString("yyyy-MM-dd hh:mm:ss"));
Logman This cannot get the year and day of the week. It's comparatively slow and also creates a temporary file and is based on the time stamps that logman puts on its log files. It will work on everything from Windows XP and above. It probably will be never used by anybody - including me - but is one more way...
@echo off
setlocal
del /q /f %temp%timestampfile_*
Logman.exe stop ts-CPU 1>nul 2>&1
Logman.exe delete ts-CPU 1>nul 2>&1
Logman.exe create counter ts-CPU -sc 2 -v mmddhhmm -max 250 -c "Processor(_Total)%% Processor Time" -o %temp%timestampfile_ >nul
Logman.exe start ts-CPU 1>nul 2>&1
Logman.exe stop ts-CPU >nul 2>&1
Logman.exe delete ts-CPU >nul 2>&1
for /f "tokens=2 delims=_." %%t in ('dir /b %temp%timestampfile_*^&del /q/f %temp%timestampfile_*') do set timestamp=%%t
echo %timestamp%
echo MM: %timestamp:~0,2%
echo dd: %timestamp:~2,2%
echo hh: %timestamp:~4,2%
echo mm: %timestamp:~6,2%
endlocal
exit /b 0
One more way with WMIC which also gives week of the year and the day of the week, but not the milliseconds (for milliseconds check foxidrive's answer):
for /f %%# in ('wMIC Path Win32_LocalTime Get /Format:value') do @for /f %%@ in ("%%#") do @set %%@
echo %day%
echo %DayOfWeek%
echo %hour%
echo %minute%
echo %month%
echo %quarter%
echo %second%
echo %weekinmonth%
echo %year%
Using TYPEPERF with some efforts to be fast and compatible with different language settings and as fast as possible:
@echo off
setlocal
:: Check if Windows is Windows XP and use Windows XP valid counter for UDP performance
::if defined USERDOMAIN_roamingprofile (set "v=v4") else (set "v=")
for /f "tokens=4 delims=. " %%# in ('ver') do if %%# GTR 5 (set "v=v4") else ("v=")
set "mon="
for /f "skip=2 delims=," %%# in ('typeperf "UDP%v%*" -si 0 -sc 1') do (
if not defined mon (
for /f "tokens=1-7 delims=.:/ " %%a in (%%#) do (
set mon=%%a
set date=%%b
set year=%%c
set hour=%%d
set minute=%%e
set sec=%%f
set ms=%%g
)
)
)
echo %year%.%mon%.%date%
echo %hour%:%minute%:%sec%.%ms%
endlocal
MSHTA allows calling JavaScript methods similar to the JScript method demonstrated in #3 above. Bear in mind that JavaScript's Date object properties involving month values are numbered from 0 to 11, not 1 to 12. So a value of 9 means October.
<!-- : Batch portion
@echo off
setlocal
for /f "delims=" %%I in ('mshta "%~f0"') do set "now.%%~I"
rem Display all variables beginning with "now."
set now.
goto :EOF
end batch / begin HTA -->
<script>
resizeTo(0,0)
var fso = new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1),
now = new Date(),
props=['getDate','getDay','getFullYear','getHours','getMilliseconds','getMinutes',
'getMonth','getSeconds','getTime','getTimezoneOffset','getUTCDate','getUTCDay',
'getUTCFullYear','getUTCHours','getUTCMilliseconds','getUTCMinutes','getUTCMonth',
'getUTCSeconds','getYear','toDateString','toGMTString','toLocaleDateString',
'toLocaleTimeString','toString','toTimeString','toUTCString','valueOf'],
output = ;
for (var i in props) {output.push(props[i] + '()=' + now[props[i]]())}
close(fso.Write(output.join('n')));
</script>
1
for powershell C:>for /f %%i in ('powershell get-date -format "{yyyyMMdd_HHmmss}"') do set datetime=%%i C:>echo %datetime%
– Samuel
May 9 '14 at 13:59
1
makecab
: this works by creating a file called~.rpt
, and searching astring
inside it, beginning withmakecab
, which is a line likeMakeCAB Report: Tue Sep 02 22:15:57 2014
. for me this command is not localized it's locale independent. This trick is relying on that. Let's hope it won't ever be, or else beware!
– n611x007
Sep 2 '14 at 20:19
7
I enjoy the opening text "Two more..." followed by 8 solutions.
– Adam Smith
Oct 20 '15 at 21:30
1
What, nomshta
hybrid? :) Mind if I edit your answer and add one? This seems to be the best collection of esoteric solutions, and it seems likemshta
belongs here.
– rojo
Oct 26 '15 at 14:19
1
The accepted solution wouldn't work for me no matter what I tried. Multiple of these solutions worked for me. (Batch and Powershell).
– Brett Wait
May 15 at 15:19
|
show 2 more comments
Two more ways that do not depend on the time settings (both taken from :How get data/time independent from localization:). And both also get the day of the week and none of them requires admin permissions!:
MAKECAB - will work on EVERY Windows system (fast, but creates a small temp file) (the foxidrive script):
@echo off
pushd "%temp%"
makecab /D RptFileName=~.rpt /D InfFileName=~.inf /f nul >nul
for /f "tokens=3-7" %%a in ('find /i "makecab"^<~.rpt') do (
set "current-date=%%e-%%b-%%c"
set "current-time=%%d"
set "weekday=%%a"
)
del ~.*
popd
echo %weekday% %current-date% %current-time%
pause
More information about get-date function.
ROBOCOPY - it's not native command for Windows XP and Windows Server 2003, but it can be downloaded from microsoft site. But is built-in in everything from Windows Vista and above:
@echo off
setlocal
for /f "skip=8 tokens=2,3,4,5,6,7,8 delims=: " %%D in ('robocopy /l * /ns /nc /ndl /nfl /np /njh /XF * /XD *') do (
set "dow=%%D"
set "month=%%E"
set "day=%%F"
set "HH=%%G"
set "MM=%%H"
set "SS=%%I"
set "year=%%J"
)
echo Day of the week: %dow%
echo Day of the month : %day%
echo Month : %month%
echo hour : %HH%
echo minutes : %MM%
echo seconds : %SS%
echo year : %year%
endlocal
And three more ways that uses other Windows script languages. They will give you more flexibility e.g. you can get week of the year, time in milliseconds and so on.
JScript/batch hybrid (need to be saved as
.bat
). JScript is available on every system form NT and above, as a part of Windows Script Host (though can be disabled through the registry it's a rare case):
@if (@X)==(@Y) @end /* ---Harmless hybrid line that begins a JScript comment
@echo off
cscript //E:JScript //nologo "%~f0"
exit /b 0
*------------------------------------------------------------------------------*/
function GetCurrentDate() {
// Today date time which will used to set as default date.
var todayDate = new Date();
todayDate = todayDate.getFullYear() + "-" +
("0" + (todayDate.getMonth() + 1)).slice(-2) + "-" +
("0" + todayDate.getDate()).slice(-2) + " " + ("0" + todayDate.getHours()).slice(-2) + ":" +
("0" + todayDate.getMinutes()).slice(-2);
return todayDate;
}
WScript.Echo(GetCurrentDate());
VSCRIPT/BATCH hybrid (Is it possible to embed and execute VBScript within a batch file without using a temporary file?) same case as JScript, but hybridization is not so perfect:
:sub echo(str) :end sub
echo off
'>nul 2>&1|| copy /Y %windir%System32doskey.exe %windir%System32'.exe >nul
'& echo current date:
'& cscript /nologo /E:vbscript "%~f0"
'& exit /b
'0 = vbGeneralDate - Default. Returns date: mm/dd/yy and time if specified: hh:mm:ss PM/AM.
'1 = vbLongDate - Returns date: weekday, monthname, year
'2 = vbShortDate - Returns date: mm/dd/yy
'3 = vbLongTime - Returns time: hh:mm:ss PM/AM
'4 = vbShortTime - Return time: hh:mm
WScript.echo Replace(FormatDateTime(Date,1),", ","-")
PowerShell - can be installed on every machine that has .NET - download from Microsoft (v1, v2, v3 (only for Windows 7 and above)). It is installed by default on everything from Windows 7/Windows Server 2008 and above:
C:> powershell get-date -format "{dd-MMM-yyyy HH:mm}"
To use it from a batch file:
for /f "delims=" %%# in ('powershell get-date -format "{dd-MMM-yyyy HH:mm}"') do @set _date=%%#
Self-compiled jscript.net/batch (never seen a Windows machine without .NET, so I think this is a pretty portable):
@if (@X)==(@Y) @end /****** silent line that start JScript comment ******
@echo off
::::::::::::::::::::::::::::::::::::
::: Compile the script ::::
::::::::::::::::::::::::::::::::::::
setlocal
if exist "%~n0.exe" goto :skip_compilation
set "frm=%SystemRoot%Microsoft.NETFramework"
:: Searching the latest installed .NET framework
for /f "tokens=* delims=" %%v in ('dir /b /s /a:d /o:-n "%SystemRoot%Microsoft.NETFrameworkv*"') do (
if exist "%%vjsc.exe" (
rem :: the javascript.net compiler
set "jsc=%%~dpsnfxvjsc.exe"
goto :break_loop
)
)
echo jsc.exe not found && exit /b 0
:break_loop
call %jsc% /nologo /out:"%~n0.exe" "%~dpsfnx0"
::::::::::::::::::::::::::::::::::::
::: End of compilation ::::
::::::::::::::::::::::::::::::::::::
:skip_compilation
"%~n0.exe"
exit /b 0
****** End of JScript comment ******/
import System;
import System.IO;
var dt=DateTime.Now;
Console.WriteLine(dt.ToString("yyyy-MM-dd hh:mm:ss"));
Logman This cannot get the year and day of the week. It's comparatively slow and also creates a temporary file and is based on the time stamps that logman puts on its log files. It will work on everything from Windows XP and above. It probably will be never used by anybody - including me - but is one more way...
@echo off
setlocal
del /q /f %temp%timestampfile_*
Logman.exe stop ts-CPU 1>nul 2>&1
Logman.exe delete ts-CPU 1>nul 2>&1
Logman.exe create counter ts-CPU -sc 2 -v mmddhhmm -max 250 -c "Processor(_Total)%% Processor Time" -o %temp%timestampfile_ >nul
Logman.exe start ts-CPU 1>nul 2>&1
Logman.exe stop ts-CPU >nul 2>&1
Logman.exe delete ts-CPU >nul 2>&1
for /f "tokens=2 delims=_." %%t in ('dir /b %temp%timestampfile_*^&del /q/f %temp%timestampfile_*') do set timestamp=%%t
echo %timestamp%
echo MM: %timestamp:~0,2%
echo dd: %timestamp:~2,2%
echo hh: %timestamp:~4,2%
echo mm: %timestamp:~6,2%
endlocal
exit /b 0
One more way with WMIC which also gives week of the year and the day of the week, but not the milliseconds (for milliseconds check foxidrive's answer):
for /f %%# in ('wMIC Path Win32_LocalTime Get /Format:value') do @for /f %%@ in ("%%#") do @set %%@
echo %day%
echo %DayOfWeek%
echo %hour%
echo %minute%
echo %month%
echo %quarter%
echo %second%
echo %weekinmonth%
echo %year%
Using TYPEPERF with some efforts to be fast and compatible with different language settings and as fast as possible:
@echo off
setlocal
:: Check if Windows is Windows XP and use Windows XP valid counter for UDP performance
::if defined USERDOMAIN_roamingprofile (set "v=v4") else (set "v=")
for /f "tokens=4 delims=. " %%# in ('ver') do if %%# GTR 5 (set "v=v4") else ("v=")
set "mon="
for /f "skip=2 delims=," %%# in ('typeperf "UDP%v%*" -si 0 -sc 1') do (
if not defined mon (
for /f "tokens=1-7 delims=.:/ " %%a in (%%#) do (
set mon=%%a
set date=%%b
set year=%%c
set hour=%%d
set minute=%%e
set sec=%%f
set ms=%%g
)
)
)
echo %year%.%mon%.%date%
echo %hour%:%minute%:%sec%.%ms%
endlocal
MSHTA allows calling JavaScript methods similar to the JScript method demonstrated in #3 above. Bear in mind that JavaScript's Date object properties involving month values are numbered from 0 to 11, not 1 to 12. So a value of 9 means October.
<!-- : Batch portion
@echo off
setlocal
for /f "delims=" %%I in ('mshta "%~f0"') do set "now.%%~I"
rem Display all variables beginning with "now."
set now.
goto :EOF
end batch / begin HTA -->
<script>
resizeTo(0,0)
var fso = new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1),
now = new Date(),
props=['getDate','getDay','getFullYear','getHours','getMilliseconds','getMinutes',
'getMonth','getSeconds','getTime','getTimezoneOffset','getUTCDate','getUTCDay',
'getUTCFullYear','getUTCHours','getUTCMilliseconds','getUTCMinutes','getUTCMonth',
'getUTCSeconds','getYear','toDateString','toGMTString','toLocaleDateString',
'toLocaleTimeString','toString','toTimeString','toUTCString','valueOf'],
output = ;
for (var i in props) {output.push(props[i] + '()=' + now[props[i]]())}
close(fso.Write(output.join('n')));
</script>
1
for powershell C:>for /f %%i in ('powershell get-date -format "{yyyyMMdd_HHmmss}"') do set datetime=%%i C:>echo %datetime%
– Samuel
May 9 '14 at 13:59
1
makecab
: this works by creating a file called~.rpt
, and searching astring
inside it, beginning withmakecab
, which is a line likeMakeCAB Report: Tue Sep 02 22:15:57 2014
. for me this command is not localized it's locale independent. This trick is relying on that. Let's hope it won't ever be, or else beware!
– n611x007
Sep 2 '14 at 20:19
7
I enjoy the opening text "Two more..." followed by 8 solutions.
– Adam Smith
Oct 20 '15 at 21:30
1
What, nomshta
hybrid? :) Mind if I edit your answer and add one? This seems to be the best collection of esoteric solutions, and it seems likemshta
belongs here.
– rojo
Oct 26 '15 at 14:19
1
The accepted solution wouldn't work for me no matter what I tried. Multiple of these solutions worked for me. (Batch and Powershell).
– Brett Wait
May 15 at 15:19
|
show 2 more comments
Two more ways that do not depend on the time settings (both taken from :How get data/time independent from localization:). And both also get the day of the week and none of them requires admin permissions!:
MAKECAB - will work on EVERY Windows system (fast, but creates a small temp file) (the foxidrive script):
@echo off
pushd "%temp%"
makecab /D RptFileName=~.rpt /D InfFileName=~.inf /f nul >nul
for /f "tokens=3-7" %%a in ('find /i "makecab"^<~.rpt') do (
set "current-date=%%e-%%b-%%c"
set "current-time=%%d"
set "weekday=%%a"
)
del ~.*
popd
echo %weekday% %current-date% %current-time%
pause
More information about get-date function.
ROBOCOPY - it's not native command for Windows XP and Windows Server 2003, but it can be downloaded from microsoft site. But is built-in in everything from Windows Vista and above:
@echo off
setlocal
for /f "skip=8 tokens=2,3,4,5,6,7,8 delims=: " %%D in ('robocopy /l * /ns /nc /ndl /nfl /np /njh /XF * /XD *') do (
set "dow=%%D"
set "month=%%E"
set "day=%%F"
set "HH=%%G"
set "MM=%%H"
set "SS=%%I"
set "year=%%J"
)
echo Day of the week: %dow%
echo Day of the month : %day%
echo Month : %month%
echo hour : %HH%
echo minutes : %MM%
echo seconds : %SS%
echo year : %year%
endlocal
And three more ways that uses other Windows script languages. They will give you more flexibility e.g. you can get week of the year, time in milliseconds and so on.
JScript/batch hybrid (need to be saved as
.bat
). JScript is available on every system form NT and above, as a part of Windows Script Host (though can be disabled through the registry it's a rare case):
@if (@X)==(@Y) @end /* ---Harmless hybrid line that begins a JScript comment
@echo off
cscript //E:JScript //nologo "%~f0"
exit /b 0
*------------------------------------------------------------------------------*/
function GetCurrentDate() {
// Today date time which will used to set as default date.
var todayDate = new Date();
todayDate = todayDate.getFullYear() + "-" +
("0" + (todayDate.getMonth() + 1)).slice(-2) + "-" +
("0" + todayDate.getDate()).slice(-2) + " " + ("0" + todayDate.getHours()).slice(-2) + ":" +
("0" + todayDate.getMinutes()).slice(-2);
return todayDate;
}
WScript.Echo(GetCurrentDate());
VSCRIPT/BATCH hybrid (Is it possible to embed and execute VBScript within a batch file without using a temporary file?) same case as JScript, but hybridization is not so perfect:
:sub echo(str) :end sub
echo off
'>nul 2>&1|| copy /Y %windir%System32doskey.exe %windir%System32'.exe >nul
'& echo current date:
'& cscript /nologo /E:vbscript "%~f0"
'& exit /b
'0 = vbGeneralDate - Default. Returns date: mm/dd/yy and time if specified: hh:mm:ss PM/AM.
'1 = vbLongDate - Returns date: weekday, monthname, year
'2 = vbShortDate - Returns date: mm/dd/yy
'3 = vbLongTime - Returns time: hh:mm:ss PM/AM
'4 = vbShortTime - Return time: hh:mm
WScript.echo Replace(FormatDateTime(Date,1),", ","-")
PowerShell - can be installed on every machine that has .NET - download from Microsoft (v1, v2, v3 (only for Windows 7 and above)). It is installed by default on everything from Windows 7/Windows Server 2008 and above:
C:> powershell get-date -format "{dd-MMM-yyyy HH:mm}"
To use it from a batch file:
for /f "delims=" %%# in ('powershell get-date -format "{dd-MMM-yyyy HH:mm}"') do @set _date=%%#
Self-compiled jscript.net/batch (never seen a Windows machine without .NET, so I think this is a pretty portable):
@if (@X)==(@Y) @end /****** silent line that start JScript comment ******
@echo off
::::::::::::::::::::::::::::::::::::
::: Compile the script ::::
::::::::::::::::::::::::::::::::::::
setlocal
if exist "%~n0.exe" goto :skip_compilation
set "frm=%SystemRoot%Microsoft.NETFramework"
:: Searching the latest installed .NET framework
for /f "tokens=* delims=" %%v in ('dir /b /s /a:d /o:-n "%SystemRoot%Microsoft.NETFrameworkv*"') do (
if exist "%%vjsc.exe" (
rem :: the javascript.net compiler
set "jsc=%%~dpsnfxvjsc.exe"
goto :break_loop
)
)
echo jsc.exe not found && exit /b 0
:break_loop
call %jsc% /nologo /out:"%~n0.exe" "%~dpsfnx0"
::::::::::::::::::::::::::::::::::::
::: End of compilation ::::
::::::::::::::::::::::::::::::::::::
:skip_compilation
"%~n0.exe"
exit /b 0
****** End of JScript comment ******/
import System;
import System.IO;
var dt=DateTime.Now;
Console.WriteLine(dt.ToString("yyyy-MM-dd hh:mm:ss"));
Logman This cannot get the year and day of the week. It's comparatively slow and also creates a temporary file and is based on the time stamps that logman puts on its log files. It will work on everything from Windows XP and above. It probably will be never used by anybody - including me - but is one more way...
@echo off
setlocal
del /q /f %temp%timestampfile_*
Logman.exe stop ts-CPU 1>nul 2>&1
Logman.exe delete ts-CPU 1>nul 2>&1
Logman.exe create counter ts-CPU -sc 2 -v mmddhhmm -max 250 -c "Processor(_Total)%% Processor Time" -o %temp%timestampfile_ >nul
Logman.exe start ts-CPU 1>nul 2>&1
Logman.exe stop ts-CPU >nul 2>&1
Logman.exe delete ts-CPU >nul 2>&1
for /f "tokens=2 delims=_." %%t in ('dir /b %temp%timestampfile_*^&del /q/f %temp%timestampfile_*') do set timestamp=%%t
echo %timestamp%
echo MM: %timestamp:~0,2%
echo dd: %timestamp:~2,2%
echo hh: %timestamp:~4,2%
echo mm: %timestamp:~6,2%
endlocal
exit /b 0
One more way with WMIC which also gives week of the year and the day of the week, but not the milliseconds (for milliseconds check foxidrive's answer):
for /f %%# in ('wMIC Path Win32_LocalTime Get /Format:value') do @for /f %%@ in ("%%#") do @set %%@
echo %day%
echo %DayOfWeek%
echo %hour%
echo %minute%
echo %month%
echo %quarter%
echo %second%
echo %weekinmonth%
echo %year%
Using TYPEPERF with some efforts to be fast and compatible with different language settings and as fast as possible:
@echo off
setlocal
:: Check if Windows is Windows XP and use Windows XP valid counter for UDP performance
::if defined USERDOMAIN_roamingprofile (set "v=v4") else (set "v=")
for /f "tokens=4 delims=. " %%# in ('ver') do if %%# GTR 5 (set "v=v4") else ("v=")
set "mon="
for /f "skip=2 delims=," %%# in ('typeperf "UDP%v%*" -si 0 -sc 1') do (
if not defined mon (
for /f "tokens=1-7 delims=.:/ " %%a in (%%#) do (
set mon=%%a
set date=%%b
set year=%%c
set hour=%%d
set minute=%%e
set sec=%%f
set ms=%%g
)
)
)
echo %year%.%mon%.%date%
echo %hour%:%minute%:%sec%.%ms%
endlocal
MSHTA allows calling JavaScript methods similar to the JScript method demonstrated in #3 above. Bear in mind that JavaScript's Date object properties involving month values are numbered from 0 to 11, not 1 to 12. So a value of 9 means October.
<!-- : Batch portion
@echo off
setlocal
for /f "delims=" %%I in ('mshta "%~f0"') do set "now.%%~I"
rem Display all variables beginning with "now."
set now.
goto :EOF
end batch / begin HTA -->
<script>
resizeTo(0,0)
var fso = new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1),
now = new Date(),
props=['getDate','getDay','getFullYear','getHours','getMilliseconds','getMinutes',
'getMonth','getSeconds','getTime','getTimezoneOffset','getUTCDate','getUTCDay',
'getUTCFullYear','getUTCHours','getUTCMilliseconds','getUTCMinutes','getUTCMonth',
'getUTCSeconds','getYear','toDateString','toGMTString','toLocaleDateString',
'toLocaleTimeString','toString','toTimeString','toUTCString','valueOf'],
output = ;
for (var i in props) {output.push(props[i] + '()=' + now[props[i]]())}
close(fso.Write(output.join('n')));
</script>
Two more ways that do not depend on the time settings (both taken from :How get data/time independent from localization:). And both also get the day of the week and none of them requires admin permissions!:
MAKECAB - will work on EVERY Windows system (fast, but creates a small temp file) (the foxidrive script):
@echo off
pushd "%temp%"
makecab /D RptFileName=~.rpt /D InfFileName=~.inf /f nul >nul
for /f "tokens=3-7" %%a in ('find /i "makecab"^<~.rpt') do (
set "current-date=%%e-%%b-%%c"
set "current-time=%%d"
set "weekday=%%a"
)
del ~.*
popd
echo %weekday% %current-date% %current-time%
pause
More information about get-date function.
ROBOCOPY - it's not native command for Windows XP and Windows Server 2003, but it can be downloaded from microsoft site. But is built-in in everything from Windows Vista and above:
@echo off
setlocal
for /f "skip=8 tokens=2,3,4,5,6,7,8 delims=: " %%D in ('robocopy /l * /ns /nc /ndl /nfl /np /njh /XF * /XD *') do (
set "dow=%%D"
set "month=%%E"
set "day=%%F"
set "HH=%%G"
set "MM=%%H"
set "SS=%%I"
set "year=%%J"
)
echo Day of the week: %dow%
echo Day of the month : %day%
echo Month : %month%
echo hour : %HH%
echo minutes : %MM%
echo seconds : %SS%
echo year : %year%
endlocal
And three more ways that uses other Windows script languages. They will give you more flexibility e.g. you can get week of the year, time in milliseconds and so on.
JScript/batch hybrid (need to be saved as
.bat
). JScript is available on every system form NT and above, as a part of Windows Script Host (though can be disabled through the registry it's a rare case):
@if (@X)==(@Y) @end /* ---Harmless hybrid line that begins a JScript comment
@echo off
cscript //E:JScript //nologo "%~f0"
exit /b 0
*------------------------------------------------------------------------------*/
function GetCurrentDate() {
// Today date time which will used to set as default date.
var todayDate = new Date();
todayDate = todayDate.getFullYear() + "-" +
("0" + (todayDate.getMonth() + 1)).slice(-2) + "-" +
("0" + todayDate.getDate()).slice(-2) + " " + ("0" + todayDate.getHours()).slice(-2) + ":" +
("0" + todayDate.getMinutes()).slice(-2);
return todayDate;
}
WScript.Echo(GetCurrentDate());
VSCRIPT/BATCH hybrid (Is it possible to embed and execute VBScript within a batch file without using a temporary file?) same case as JScript, but hybridization is not so perfect:
:sub echo(str) :end sub
echo off
'>nul 2>&1|| copy /Y %windir%System32doskey.exe %windir%System32'.exe >nul
'& echo current date:
'& cscript /nologo /E:vbscript "%~f0"
'& exit /b
'0 = vbGeneralDate - Default. Returns date: mm/dd/yy and time if specified: hh:mm:ss PM/AM.
'1 = vbLongDate - Returns date: weekday, monthname, year
'2 = vbShortDate - Returns date: mm/dd/yy
'3 = vbLongTime - Returns time: hh:mm:ss PM/AM
'4 = vbShortTime - Return time: hh:mm
WScript.echo Replace(FormatDateTime(Date,1),", ","-")
PowerShell - can be installed on every machine that has .NET - download from Microsoft (v1, v2, v3 (only for Windows 7 and above)). It is installed by default on everything from Windows 7/Windows Server 2008 and above:
C:> powershell get-date -format "{dd-MMM-yyyy HH:mm}"
To use it from a batch file:
for /f "delims=" %%# in ('powershell get-date -format "{dd-MMM-yyyy HH:mm}"') do @set _date=%%#
Self-compiled jscript.net/batch (never seen a Windows machine without .NET, so I think this is a pretty portable):
@if (@X)==(@Y) @end /****** silent line that start JScript comment ******
@echo off
::::::::::::::::::::::::::::::::::::
::: Compile the script ::::
::::::::::::::::::::::::::::::::::::
setlocal
if exist "%~n0.exe" goto :skip_compilation
set "frm=%SystemRoot%Microsoft.NETFramework"
:: Searching the latest installed .NET framework
for /f "tokens=* delims=" %%v in ('dir /b /s /a:d /o:-n "%SystemRoot%Microsoft.NETFrameworkv*"') do (
if exist "%%vjsc.exe" (
rem :: the javascript.net compiler
set "jsc=%%~dpsnfxvjsc.exe"
goto :break_loop
)
)
echo jsc.exe not found && exit /b 0
:break_loop
call %jsc% /nologo /out:"%~n0.exe" "%~dpsfnx0"
::::::::::::::::::::::::::::::::::::
::: End of compilation ::::
::::::::::::::::::::::::::::::::::::
:skip_compilation
"%~n0.exe"
exit /b 0
****** End of JScript comment ******/
import System;
import System.IO;
var dt=DateTime.Now;
Console.WriteLine(dt.ToString("yyyy-MM-dd hh:mm:ss"));
Logman This cannot get the year and day of the week. It's comparatively slow and also creates a temporary file and is based on the time stamps that logman puts on its log files. It will work on everything from Windows XP and above. It probably will be never used by anybody - including me - but is one more way...
@echo off
setlocal
del /q /f %temp%timestampfile_*
Logman.exe stop ts-CPU 1>nul 2>&1
Logman.exe delete ts-CPU 1>nul 2>&1
Logman.exe create counter ts-CPU -sc 2 -v mmddhhmm -max 250 -c "Processor(_Total)%% Processor Time" -o %temp%timestampfile_ >nul
Logman.exe start ts-CPU 1>nul 2>&1
Logman.exe stop ts-CPU >nul 2>&1
Logman.exe delete ts-CPU >nul 2>&1
for /f "tokens=2 delims=_." %%t in ('dir /b %temp%timestampfile_*^&del /q/f %temp%timestampfile_*') do set timestamp=%%t
echo %timestamp%
echo MM: %timestamp:~0,2%
echo dd: %timestamp:~2,2%
echo hh: %timestamp:~4,2%
echo mm: %timestamp:~6,2%
endlocal
exit /b 0
One more way with WMIC which also gives week of the year and the day of the week, but not the milliseconds (for milliseconds check foxidrive's answer):
for /f %%# in ('wMIC Path Win32_LocalTime Get /Format:value') do @for /f %%@ in ("%%#") do @set %%@
echo %day%
echo %DayOfWeek%
echo %hour%
echo %minute%
echo %month%
echo %quarter%
echo %second%
echo %weekinmonth%
echo %year%
Using TYPEPERF with some efforts to be fast and compatible with different language settings and as fast as possible:
@echo off
setlocal
:: Check if Windows is Windows XP and use Windows XP valid counter for UDP performance
::if defined USERDOMAIN_roamingprofile (set "v=v4") else (set "v=")
for /f "tokens=4 delims=. " %%# in ('ver') do if %%# GTR 5 (set "v=v4") else ("v=")
set "mon="
for /f "skip=2 delims=," %%# in ('typeperf "UDP%v%*" -si 0 -sc 1') do (
if not defined mon (
for /f "tokens=1-7 delims=.:/ " %%a in (%%#) do (
set mon=%%a
set date=%%b
set year=%%c
set hour=%%d
set minute=%%e
set sec=%%f
set ms=%%g
)
)
)
echo %year%.%mon%.%date%
echo %hour%:%minute%:%sec%.%ms%
endlocal
MSHTA allows calling JavaScript methods similar to the JScript method demonstrated in #3 above. Bear in mind that JavaScript's Date object properties involving month values are numbered from 0 to 11, not 1 to 12. So a value of 9 means October.
<!-- : Batch portion
@echo off
setlocal
for /f "delims=" %%I in ('mshta "%~f0"') do set "now.%%~I"
rem Display all variables beginning with "now."
set now.
goto :EOF
end batch / begin HTA -->
<script>
resizeTo(0,0)
var fso = new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1),
now = new Date(),
props=['getDate','getDay','getFullYear','getHours','getMilliseconds','getMinutes',
'getMonth','getSeconds','getTime','getTimezoneOffset','getUTCDate','getUTCDay',
'getUTCFullYear','getUTCHours','getUTCMilliseconds','getUTCMinutes','getUTCMonth',
'getUTCSeconds','getYear','toDateString','toGMTString','toLocaleDateString',
'toLocaleTimeString','toString','toTimeString','toUTCString','valueOf'],
output = ;
for (var i in props) {output.push(props[i] + '()=' + now[props[i]]())}
close(fso.Write(output.join('n')));
</script>
edited Jul 15 '17 at 17:52
Peter Mortensen
13.4k1983111
13.4k1983111
answered Nov 5 '13 at 21:21
npocmaka
41.4k1184127
41.4k1184127
1
for powershell C:>for /f %%i in ('powershell get-date -format "{yyyyMMdd_HHmmss}"') do set datetime=%%i C:>echo %datetime%
– Samuel
May 9 '14 at 13:59
1
makecab
: this works by creating a file called~.rpt
, and searching astring
inside it, beginning withmakecab
, which is a line likeMakeCAB Report: Tue Sep 02 22:15:57 2014
. for me this command is not localized it's locale independent. This trick is relying on that. Let's hope it won't ever be, or else beware!
– n611x007
Sep 2 '14 at 20:19
7
I enjoy the opening text "Two more..." followed by 8 solutions.
– Adam Smith
Oct 20 '15 at 21:30
1
What, nomshta
hybrid? :) Mind if I edit your answer and add one? This seems to be the best collection of esoteric solutions, and it seems likemshta
belongs here.
– rojo
Oct 26 '15 at 14:19
1
The accepted solution wouldn't work for me no matter what I tried. Multiple of these solutions worked for me. (Batch and Powershell).
– Brett Wait
May 15 at 15:19
|
show 2 more comments
1
for powershell C:>for /f %%i in ('powershell get-date -format "{yyyyMMdd_HHmmss}"') do set datetime=%%i C:>echo %datetime%
– Samuel
May 9 '14 at 13:59
1
makecab
: this works by creating a file called~.rpt
, and searching astring
inside it, beginning withmakecab
, which is a line likeMakeCAB Report: Tue Sep 02 22:15:57 2014
. for me this command is not localized it's locale independent. This trick is relying on that. Let's hope it won't ever be, or else beware!
– n611x007
Sep 2 '14 at 20:19
7
I enjoy the opening text "Two more..." followed by 8 solutions.
– Adam Smith
Oct 20 '15 at 21:30
1
What, nomshta
hybrid? :) Mind if I edit your answer and add one? This seems to be the best collection of esoteric solutions, and it seems likemshta
belongs here.
– rojo
Oct 26 '15 at 14:19
1
The accepted solution wouldn't work for me no matter what I tried. Multiple of these solutions worked for me. (Batch and Powershell).
– Brett Wait
May 15 at 15:19
1
1
for powershell C:>for /f %%i in ('powershell get-date -format "{yyyyMMdd_HHmmss}"') do set datetime=%%i C:>echo %datetime%
– Samuel
May 9 '14 at 13:59
for powershell C:>for /f %%i in ('powershell get-date -format "{yyyyMMdd_HHmmss}"') do set datetime=%%i C:>echo %datetime%
– Samuel
May 9 '14 at 13:59
1
1
makecab
: this works by creating a file called ~.rpt
, and searching a string
inside it, beginning with makecab
, which is a line like MakeCAB Report: Tue Sep 02 22:15:57 2014
. for me this command is not localized it's locale independent. This trick is relying on that. Let's hope it won't ever be, or else beware!– n611x007
Sep 2 '14 at 20:19
makecab
: this works by creating a file called ~.rpt
, and searching a string
inside it, beginning with makecab
, which is a line like MakeCAB Report: Tue Sep 02 22:15:57 2014
. for me this command is not localized it's locale independent. This trick is relying on that. Let's hope it won't ever be, or else beware!– n611x007
Sep 2 '14 at 20:19
7
7
I enjoy the opening text "Two more..." followed by 8 solutions.
– Adam Smith
Oct 20 '15 at 21:30
I enjoy the opening text "Two more..." followed by 8 solutions.
– Adam Smith
Oct 20 '15 at 21:30
1
1
What, no
mshta
hybrid? :) Mind if I edit your answer and add one? This seems to be the best collection of esoteric solutions, and it seems like mshta
belongs here.– rojo
Oct 26 '15 at 14:19
What, no
mshta
hybrid? :) Mind if I edit your answer and add one? This seems to be the best collection of esoteric solutions, and it seems like mshta
belongs here.– rojo
Oct 26 '15 at 14:19
1
1
The accepted solution wouldn't work for me no matter what I tried. Multiple of these solutions worked for me. (Batch and Powershell).
– Brett Wait
May 15 at 15:19
The accepted solution wouldn't work for me no matter what I tried. Multiple of these solutions worked for me. (Batch and Powershell).
– Brett Wait
May 15 at 15:19
|
show 2 more comments
Here's a variant from alt.msdos.batch.nt that works local-independently.
Put this in a text file, e.g. getDate.cmd
-----------8<------8<------------ snip -- snip ----------8<-------------
:: Works on any NT/2k machine independent of regional date settings
@ECHO off
SETLOCAL ENABLEEXTENSIONS
if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
for /f "tokens=2-4 delims=(-)" %%a in ('echo:^|date') do (
for /f "tokens=%toks% delims=.-/ " %%i in ('date/t') do (
set '%%a'=%%i
set '%%b'=%%j
set '%%c'=%%k))
if %'yy'% LSS 100 set 'yy'=20%'yy'%
set Today=%'yy'%-%'mm'%-%'dd'%
ENDLOCAL & SET v_year=%'yy'%& SET v_month=%'mm'%& SET v_day=%'dd'%
ECHO Today is Year: [%V_Year%] Month: [%V_Month%] Day: [%V_Day%]
:EOF
-----------8<------8<------------ snip -- snip ----------8<-------------
To get the code to work sans error msg's to stderr, I had to add the single quotes arount the variable assignments for %%a, %%b and %%c. My locale (PT) was causing errors at one stage in the looping/parsing where stuff like "set =20" was getting executed. The quotes yield a token (albeit empty) for the left-hand side of the assignment statement.
The downside is the messy locale variable names: 'yy', 'mm' and 'dd'. But hey, who cares!
3
This is perfect and is the simplest and most elegant approach i've seen to date.
– Doug
Dec 14 '11 at 0:25
1
See also Jeroen's enhancements, needed as not all locales use the stringsdd
,mm
andyy
in the output ofecho:^|date
.
– Arjan
Jun 23 '12 at 10:01
1
This should be the accepted answer +1
– Inder Kumar Rathore
Mar 7 '13 at 10:53
add a comment |
Here's a variant from alt.msdos.batch.nt that works local-independently.
Put this in a text file, e.g. getDate.cmd
-----------8<------8<------------ snip -- snip ----------8<-------------
:: Works on any NT/2k machine independent of regional date settings
@ECHO off
SETLOCAL ENABLEEXTENSIONS
if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
for /f "tokens=2-4 delims=(-)" %%a in ('echo:^|date') do (
for /f "tokens=%toks% delims=.-/ " %%i in ('date/t') do (
set '%%a'=%%i
set '%%b'=%%j
set '%%c'=%%k))
if %'yy'% LSS 100 set 'yy'=20%'yy'%
set Today=%'yy'%-%'mm'%-%'dd'%
ENDLOCAL & SET v_year=%'yy'%& SET v_month=%'mm'%& SET v_day=%'dd'%
ECHO Today is Year: [%V_Year%] Month: [%V_Month%] Day: [%V_Day%]
:EOF
-----------8<------8<------------ snip -- snip ----------8<-------------
To get the code to work sans error msg's to stderr, I had to add the single quotes arount the variable assignments for %%a, %%b and %%c. My locale (PT) was causing errors at one stage in the looping/parsing where stuff like "set =20" was getting executed. The quotes yield a token (albeit empty) for the left-hand side of the assignment statement.
The downside is the messy locale variable names: 'yy', 'mm' and 'dd'. But hey, who cares!
3
This is perfect and is the simplest and most elegant approach i've seen to date.
– Doug
Dec 14 '11 at 0:25
1
See also Jeroen's enhancements, needed as not all locales use the stringsdd
,mm
andyy
in the output ofecho:^|date
.
– Arjan
Jun 23 '12 at 10:01
1
This should be the accepted answer +1
– Inder Kumar Rathore
Mar 7 '13 at 10:53
add a comment |
Here's a variant from alt.msdos.batch.nt that works local-independently.
Put this in a text file, e.g. getDate.cmd
-----------8<------8<------------ snip -- snip ----------8<-------------
:: Works on any NT/2k machine independent of regional date settings
@ECHO off
SETLOCAL ENABLEEXTENSIONS
if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
for /f "tokens=2-4 delims=(-)" %%a in ('echo:^|date') do (
for /f "tokens=%toks% delims=.-/ " %%i in ('date/t') do (
set '%%a'=%%i
set '%%b'=%%j
set '%%c'=%%k))
if %'yy'% LSS 100 set 'yy'=20%'yy'%
set Today=%'yy'%-%'mm'%-%'dd'%
ENDLOCAL & SET v_year=%'yy'%& SET v_month=%'mm'%& SET v_day=%'dd'%
ECHO Today is Year: [%V_Year%] Month: [%V_Month%] Day: [%V_Day%]
:EOF
-----------8<------8<------------ snip -- snip ----------8<-------------
To get the code to work sans error msg's to stderr, I had to add the single quotes arount the variable assignments for %%a, %%b and %%c. My locale (PT) was causing errors at one stage in the looping/parsing where stuff like "set =20" was getting executed. The quotes yield a token (albeit empty) for the left-hand side of the assignment statement.
The downside is the messy locale variable names: 'yy', 'mm' and 'dd'. But hey, who cares!
Here's a variant from alt.msdos.batch.nt that works local-independently.
Put this in a text file, e.g. getDate.cmd
-----------8<------8<------------ snip -- snip ----------8<-------------
:: Works on any NT/2k machine independent of regional date settings
@ECHO off
SETLOCAL ENABLEEXTENSIONS
if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
for /f "tokens=2-4 delims=(-)" %%a in ('echo:^|date') do (
for /f "tokens=%toks% delims=.-/ " %%i in ('date/t') do (
set '%%a'=%%i
set '%%b'=%%j
set '%%c'=%%k))
if %'yy'% LSS 100 set 'yy'=20%'yy'%
set Today=%'yy'%-%'mm'%-%'dd'%
ENDLOCAL & SET v_year=%'yy'%& SET v_month=%'mm'%& SET v_day=%'dd'%
ECHO Today is Year: [%V_Year%] Month: [%V_Month%] Day: [%V_Day%]
:EOF
-----------8<------8<------------ snip -- snip ----------8<-------------
To get the code to work sans error msg's to stderr, I had to add the single quotes arount the variable assignments for %%a, %%b and %%c. My locale (PT) was causing errors at one stage in the looping/parsing where stuff like "set =20" was getting executed. The quotes yield a token (albeit empty) for the left-hand side of the assignment statement.
The downside is the messy locale variable names: 'yy', 'mm' and 'dd'. But hey, who cares!
answered Jul 8 '10 at 10:50
vMax
42142
42142
3
This is perfect and is the simplest and most elegant approach i've seen to date.
– Doug
Dec 14 '11 at 0:25
1
See also Jeroen's enhancements, needed as not all locales use the stringsdd
,mm
andyy
in the output ofecho:^|date
.
– Arjan
Jun 23 '12 at 10:01
1
This should be the accepted answer +1
– Inder Kumar Rathore
Mar 7 '13 at 10:53
add a comment |
3
This is perfect and is the simplest and most elegant approach i've seen to date.
– Doug
Dec 14 '11 at 0:25
1
See also Jeroen's enhancements, needed as not all locales use the stringsdd
,mm
andyy
in the output ofecho:^|date
.
– Arjan
Jun 23 '12 at 10:01
1
This should be the accepted answer +1
– Inder Kumar Rathore
Mar 7 '13 at 10:53
3
3
This is perfect and is the simplest and most elegant approach i've seen to date.
– Doug
Dec 14 '11 at 0:25
This is perfect and is the simplest and most elegant approach i've seen to date.
– Doug
Dec 14 '11 at 0:25
1
1
See also Jeroen's enhancements, needed as not all locales use the strings
dd
, mm
and yy
in the output of echo:^|date
.– Arjan
Jun 23 '12 at 10:01
See also Jeroen's enhancements, needed as not all locales use the strings
dd
, mm
and yy
in the output of echo:^|date
.– Arjan
Jun 23 '12 at 10:01
1
1
This should be the accepted answer +1
– Inder Kumar Rathore
Mar 7 '13 at 10:53
This should be the accepted answer +1
– Inder Kumar Rathore
Mar 7 '13 at 10:53
add a comment |
I use this (again not region independent (UK))
set bklog=%date:~6,4%-%date:~3,2%-%date:~0,2%_%time:~0,2%%time:~3,2%
See Cmd.exe Environment Variables with Colon and Tilde on this little known but very efficient technique. (A pointer to a Microsoft authoritative reference would be appreciated.)
– DavidRR
Dec 16 '13 at 0:33
Here's Microsoft's Batch File Reference for Windows XP. That reference includes Using batch parameters. Unfortunately, no discussion of the 'slicing' technique.
– DavidRR
Dec 16 '13 at 0:51
This doesn't quite work for me. Maybe it is something to do with regional settings? I get an output of "/15/- 1-We_1009" when running it on Wednesday, October 15, 2014.
– Joel B
Oct 15 '14 at 16:11
add a comment |
I use this (again not region independent (UK))
set bklog=%date:~6,4%-%date:~3,2%-%date:~0,2%_%time:~0,2%%time:~3,2%
See Cmd.exe Environment Variables with Colon and Tilde on this little known but very efficient technique. (A pointer to a Microsoft authoritative reference would be appreciated.)
– DavidRR
Dec 16 '13 at 0:33
Here's Microsoft's Batch File Reference for Windows XP. That reference includes Using batch parameters. Unfortunately, no discussion of the 'slicing' technique.
– DavidRR
Dec 16 '13 at 0:51
This doesn't quite work for me. Maybe it is something to do with regional settings? I get an output of "/15/- 1-We_1009" when running it on Wednesday, October 15, 2014.
– Joel B
Oct 15 '14 at 16:11
add a comment |
I use this (again not region independent (UK))
set bklog=%date:~6,4%-%date:~3,2%-%date:~0,2%_%time:~0,2%%time:~3,2%
I use this (again not region independent (UK))
set bklog=%date:~6,4%-%date:~3,2%-%date:~0,2%_%time:~0,2%%time:~3,2%
edited Oct 15 '12 at 8:48
bluish
13.7k1693146
13.7k1693146
answered Apr 12 '09 at 13:13
Dale Walker
See Cmd.exe Environment Variables with Colon and Tilde on this little known but very efficient technique. (A pointer to a Microsoft authoritative reference would be appreciated.)
– DavidRR
Dec 16 '13 at 0:33
Here's Microsoft's Batch File Reference for Windows XP. That reference includes Using batch parameters. Unfortunately, no discussion of the 'slicing' technique.
– DavidRR
Dec 16 '13 at 0:51
This doesn't quite work for me. Maybe it is something to do with regional settings? I get an output of "/15/- 1-We_1009" when running it on Wednesday, October 15, 2014.
– Joel B
Oct 15 '14 at 16:11
add a comment |
See Cmd.exe Environment Variables with Colon and Tilde on this little known but very efficient technique. (A pointer to a Microsoft authoritative reference would be appreciated.)
– DavidRR
Dec 16 '13 at 0:33
Here's Microsoft's Batch File Reference for Windows XP. That reference includes Using batch parameters. Unfortunately, no discussion of the 'slicing' technique.
– DavidRR
Dec 16 '13 at 0:51
This doesn't quite work for me. Maybe it is something to do with regional settings? I get an output of "/15/- 1-We_1009" when running it on Wednesday, October 15, 2014.
– Joel B
Oct 15 '14 at 16:11
See Cmd.exe Environment Variables with Colon and Tilde on this little known but very efficient technique. (A pointer to a Microsoft authoritative reference would be appreciated.)
– DavidRR
Dec 16 '13 at 0:33
See Cmd.exe Environment Variables with Colon and Tilde on this little known but very efficient technique. (A pointer to a Microsoft authoritative reference would be appreciated.)
– DavidRR
Dec 16 '13 at 0:33
Here's Microsoft's Batch File Reference for Windows XP. That reference includes Using batch parameters. Unfortunately, no discussion of the 'slicing' technique.
– DavidRR
Dec 16 '13 at 0:51
Here's Microsoft's Batch File Reference for Windows XP. That reference includes Using batch parameters. Unfortunately, no discussion of the 'slicing' technique.
– DavidRR
Dec 16 '13 at 0:51
This doesn't quite work for me. Maybe it is something to do with regional settings? I get an output of "/15/- 1-We_1009" when running it on Wednesday, October 15, 2014.
– Joel B
Oct 15 '14 at 16:11
This doesn't quite work for me. Maybe it is something to do with regional settings? I get an output of "/15/- 1-We_1009" when running it on Wednesday, October 15, 2014.
– Joel B
Oct 15 '14 at 16:11
add a comment |
Unfortunately this is not immune to regional settings, but it does what you want.
set hour=%time:~0,2%
if "%time:~0,1%"==" " set hour=0%time:~1,1%
set _my_datetime=%date:~10,4%-%date:~4,2%-%date:~7,2%_%hour%%time:~3,2%
Amazing the stuff you can find on Wikipedia.
1
Mark - Found Cmd.exe Environment Variables with Colon and Tilde which describes the variable 'slicing' technique exhibited in your answer. Not finding that info any longer in the Wikipedia article. Would like to find an authoritative reference from Microsoft.
– DavidRR
Dec 16 '13 at 0:41
1
Here's Microsoft's Batch File Reference for Windows XP. That reference includes Using batch parameters. Unfortunately, no discussion of the 'slicing' technique.
– DavidRR
Dec 16 '13 at 0:50
add a comment |
Unfortunately this is not immune to regional settings, but it does what you want.
set hour=%time:~0,2%
if "%time:~0,1%"==" " set hour=0%time:~1,1%
set _my_datetime=%date:~10,4%-%date:~4,2%-%date:~7,2%_%hour%%time:~3,2%
Amazing the stuff you can find on Wikipedia.
1
Mark - Found Cmd.exe Environment Variables with Colon and Tilde which describes the variable 'slicing' technique exhibited in your answer. Not finding that info any longer in the Wikipedia article. Would like to find an authoritative reference from Microsoft.
– DavidRR
Dec 16 '13 at 0:41
1
Here's Microsoft's Batch File Reference for Windows XP. That reference includes Using batch parameters. Unfortunately, no discussion of the 'slicing' technique.
– DavidRR
Dec 16 '13 at 0:50
add a comment |
Unfortunately this is not immune to regional settings, but it does what you want.
set hour=%time:~0,2%
if "%time:~0,1%"==" " set hour=0%time:~1,1%
set _my_datetime=%date:~10,4%-%date:~4,2%-%date:~7,2%_%hour%%time:~3,2%
Amazing the stuff you can find on Wikipedia.
Unfortunately this is not immune to regional settings, but it does what you want.
set hour=%time:~0,2%
if "%time:~0,1%"==" " set hour=0%time:~1,1%
set _my_datetime=%date:~10,4%-%date:~4,2%-%date:~7,2%_%hour%%time:~3,2%
Amazing the stuff you can find on Wikipedia.
answered Oct 14 '08 at 22:43
Mark Ransom
222k29278504
222k29278504
1
Mark - Found Cmd.exe Environment Variables with Colon and Tilde which describes the variable 'slicing' technique exhibited in your answer. Not finding that info any longer in the Wikipedia article. Would like to find an authoritative reference from Microsoft.
– DavidRR
Dec 16 '13 at 0:41
1
Here's Microsoft's Batch File Reference for Windows XP. That reference includes Using batch parameters. Unfortunately, no discussion of the 'slicing' technique.
– DavidRR
Dec 16 '13 at 0:50
add a comment |
1
Mark - Found Cmd.exe Environment Variables with Colon and Tilde which describes the variable 'slicing' technique exhibited in your answer. Not finding that info any longer in the Wikipedia article. Would like to find an authoritative reference from Microsoft.
– DavidRR
Dec 16 '13 at 0:41
1
Here's Microsoft's Batch File Reference for Windows XP. That reference includes Using batch parameters. Unfortunately, no discussion of the 'slicing' technique.
– DavidRR
Dec 16 '13 at 0:50
1
1
Mark - Found Cmd.exe Environment Variables with Colon and Tilde which describes the variable 'slicing' technique exhibited in your answer. Not finding that info any longer in the Wikipedia article. Would like to find an authoritative reference from Microsoft.
– DavidRR
Dec 16 '13 at 0:41
Mark - Found Cmd.exe Environment Variables with Colon and Tilde which describes the variable 'slicing' technique exhibited in your answer. Not finding that info any longer in the Wikipedia article. Would like to find an authoritative reference from Microsoft.
– DavidRR
Dec 16 '13 at 0:41
1
1
Here's Microsoft's Batch File Reference for Windows XP. That reference includes Using batch parameters. Unfortunately, no discussion of the 'slicing' technique.
– DavidRR
Dec 16 '13 at 0:50
Here's Microsoft's Batch File Reference for Windows XP. That reference includes Using batch parameters. Unfortunately, no discussion of the 'slicing' technique.
– DavidRR
Dec 16 '13 at 0:50
add a comment |
Please use the following script to get the current day in the command line:
echo %Date:~0,3%day
6
Played a bit around with this, it is the shortest I found to get Date and Time: echo %date% %time%
– loomi
Nov 23 '12 at 8:49
4
I gotThuday
.
– NReilingh
Dec 5 '13 at 17:37
add a comment |
Please use the following script to get the current day in the command line:
echo %Date:~0,3%day
6
Played a bit around with this, it is the shortest I found to get Date and Time: echo %date% %time%
– loomi
Nov 23 '12 at 8:49
4
I gotThuday
.
– NReilingh
Dec 5 '13 at 17:37
add a comment |
Please use the following script to get the current day in the command line:
echo %Date:~0,3%day
Please use the following script to get the current day in the command line:
echo %Date:~0,3%day
edited Dec 12 '11 at 11:50
user527987
19k53552
19k53552
answered Jul 15 '11 at 13:00
sudipto roy
17112
17112
6
Played a bit around with this, it is the shortest I found to get Date and Time: echo %date% %time%
– loomi
Nov 23 '12 at 8:49
4
I gotThuday
.
– NReilingh
Dec 5 '13 at 17:37
add a comment |
6
Played a bit around with this, it is the shortest I found to get Date and Time: echo %date% %time%
– loomi
Nov 23 '12 at 8:49
4
I gotThuday
.
– NReilingh
Dec 5 '13 at 17:37
6
6
Played a bit around with this, it is the shortest I found to get Date and Time: echo %date% %time%
– loomi
Nov 23 '12 at 8:49
Played a bit around with this, it is the shortest I found to get Date and Time: echo %date% %time%
– loomi
Nov 23 '12 at 8:49
4
4
I got
Thuday
.– NReilingh
Dec 5 '13 at 17:37
I got
Thuday
.– NReilingh
Dec 5 '13 at 17:37
add a comment |
The first four lines of this code will give you reliable YY DD MM YYYY HH Min Sec variables in Windows XP Professional and higher.
@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"
set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%" & set "fullstamp=%YYYY%-%MM%-%DD%_%HH%%Min%-%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause
add a comment |
The first four lines of this code will give you reliable YY DD MM YYYY HH Min Sec variables in Windows XP Professional and higher.
@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"
set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%" & set "fullstamp=%YYYY%-%MM%-%DD%_%HH%%Min%-%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause
add a comment |
The first four lines of this code will give you reliable YY DD MM YYYY HH Min Sec variables in Windows XP Professional and higher.
@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"
set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%" & set "fullstamp=%YYYY%-%MM%-%DD%_%HH%%Min%-%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause
The first four lines of this code will give you reliable YY DD MM YYYY HH Min Sec variables in Windows XP Professional and higher.
@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"
set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%" & set "fullstamp=%YYYY%-%MM%-%DD%_%HH%%Min%-%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause
edited Jul 15 '17 at 17:58
Peter Mortensen
13.4k1983111
13.4k1983111
answered Sep 7 '14 at 19:47
foxidrive
33.7k73457
33.7k73457
add a comment |
add a comment |
Another way (credit):
@For /F "tokens=2,3,4 delims=/ " %%A in ('Date /t') do @(
Set Month=%%A
Set Day=%%B
Set Year=%%C
)
@echo DAY = %Day%
@echo Month = %Month%
@echo Year = %Year%
Note that both my answers here are still reliant on the order of the day and month as determined by regional settings - not sure how to work around that.
add a comment |
Another way (credit):
@For /F "tokens=2,3,4 delims=/ " %%A in ('Date /t') do @(
Set Month=%%A
Set Day=%%B
Set Year=%%C
)
@echo DAY = %Day%
@echo Month = %Month%
@echo Year = %Year%
Note that both my answers here are still reliant on the order of the day and month as determined by regional settings - not sure how to work around that.
add a comment |
Another way (credit):
@For /F "tokens=2,3,4 delims=/ " %%A in ('Date /t') do @(
Set Month=%%A
Set Day=%%B
Set Year=%%C
)
@echo DAY = %Day%
@echo Month = %Month%
@echo Year = %Year%
Note that both my answers here are still reliant on the order of the day and month as determined by regional settings - not sure how to work around that.
Another way (credit):
@For /F "tokens=2,3,4 delims=/ " %%A in ('Date /t') do @(
Set Month=%%A
Set Day=%%B
Set Year=%%C
)
@echo DAY = %Day%
@echo Month = %Month%
@echo Year = %Year%
Note that both my answers here are still reliant on the order of the day and month as determined by regional settings - not sure how to work around that.
answered Oct 14 '08 at 22:36
J c
5,58812229
5,58812229
add a comment |
add a comment |
"d:Program Files7-Zip7z.exe" a -r code_%date:~10,4%-%date:~4,2%-%date:~7,2%.zip
great.. works as a cake..
– Saravanan
Aug 4 '11 at 3:44
http://www.dotnetperls.com/7-zip-examples
has some good points may be useful for some one in future.
– Saravanan
Aug 4 '11 at 3:47
3
-1 surely this is not independent of date format.
– barlop
Nov 26 '13 at 16:05
add a comment |
"d:Program Files7-Zip7z.exe" a -r code_%date:~10,4%-%date:~4,2%-%date:~7,2%.zip
great.. works as a cake..
– Saravanan
Aug 4 '11 at 3:44
http://www.dotnetperls.com/7-zip-examples
has some good points may be useful for some one in future.
– Saravanan
Aug 4 '11 at 3:47
3
-1 surely this is not independent of date format.
– barlop
Nov 26 '13 at 16:05
add a comment |
"d:Program Files7-Zip7z.exe" a -r code_%date:~10,4%-%date:~4,2%-%date:~7,2%.zip
"d:Program Files7-Zip7z.exe" a -r code_%date:~10,4%-%date:~4,2%-%date:~7,2%.zip
edited Mar 20 '10 at 11:13
Jeff Atwood
45.2k45139148
45.2k45139148
answered Dec 4 '09 at 19:44
DigiP
14712
14712
great.. works as a cake..
– Saravanan
Aug 4 '11 at 3:44
http://www.dotnetperls.com/7-zip-examples
has some good points may be useful for some one in future.
– Saravanan
Aug 4 '11 at 3:47
3
-1 surely this is not independent of date format.
– barlop
Nov 26 '13 at 16:05
add a comment |
great.. works as a cake..
– Saravanan
Aug 4 '11 at 3:44
http://www.dotnetperls.com/7-zip-examples
has some good points may be useful for some one in future.
– Saravanan
Aug 4 '11 at 3:47
3
-1 surely this is not independent of date format.
– barlop
Nov 26 '13 at 16:05
great.. works as a cake..
– Saravanan
Aug 4 '11 at 3:44
great.. works as a cake..
– Saravanan
Aug 4 '11 at 3:44
http://www.dotnetperls.com/7-zip-examples
has some good points may be useful for some one in future.– Saravanan
Aug 4 '11 at 3:47
http://www.dotnetperls.com/7-zip-examples
has some good points may be useful for some one in future.– Saravanan
Aug 4 '11 at 3:47
3
3
-1 surely this is not independent of date format.
– barlop
Nov 26 '13 at 16:05
-1 surely this is not independent of date format.
– barlop
Nov 26 '13 at 16:05
add a comment |
This isn't really briefer but might be a more flexible way (credit):
FOR /F "TOKENS=1* DELIMS= " %%A IN ('DATE/T') DO SET CDATE=%%B
FOR /F "TOKENS=1,2 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET mm=%%B
FOR /F "TOKENS=1,2 DELIMS=/ eol=/" %%A IN ('echo %CDATE%') DO SET dd=%%B
FOR /F "TOKENS=2,3 DELIMS=/ " %%A IN ('echo %CDATE%') DO SET yyyy=%%B
SET date=%mm%%dd%%yyyy%
add a comment |
This isn't really briefer but might be a more flexible way (credit):
FOR /F "TOKENS=1* DELIMS= " %%A IN ('DATE/T') DO SET CDATE=%%B
FOR /F "TOKENS=1,2 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET mm=%%B
FOR /F "TOKENS=1,2 DELIMS=/ eol=/" %%A IN ('echo %CDATE%') DO SET dd=%%B
FOR /F "TOKENS=2,3 DELIMS=/ " %%A IN ('echo %CDATE%') DO SET yyyy=%%B
SET date=%mm%%dd%%yyyy%
add a comment |
This isn't really briefer but might be a more flexible way (credit):
FOR /F "TOKENS=1* DELIMS= " %%A IN ('DATE/T') DO SET CDATE=%%B
FOR /F "TOKENS=1,2 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET mm=%%B
FOR /F "TOKENS=1,2 DELIMS=/ eol=/" %%A IN ('echo %CDATE%') DO SET dd=%%B
FOR /F "TOKENS=2,3 DELIMS=/ " %%A IN ('echo %CDATE%') DO SET yyyy=%%B
SET date=%mm%%dd%%yyyy%
This isn't really briefer but might be a more flexible way (credit):
FOR /F "TOKENS=1* DELIMS= " %%A IN ('DATE/T') DO SET CDATE=%%B
FOR /F "TOKENS=1,2 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET mm=%%B
FOR /F "TOKENS=1,2 DELIMS=/ eol=/" %%A IN ('echo %CDATE%') DO SET dd=%%B
FOR /F "TOKENS=2,3 DELIMS=/ " %%A IN ('echo %CDATE%') DO SET yyyy=%%B
SET date=%mm%%dd%%yyyy%
edited Sep 23 '16 at 21:04
sblom
22.6k45386
22.6k45386
answered Oct 14 '08 at 22:31
J c
5,58812229
5,58812229
add a comment |
add a comment |
Here's a way to get date time in a single line:
for /f "tokens=2,3,4,5,6 usebackq delims=:/ " %a in ('%date% %time%') do echo %c-%a-%b %d%e
In the US this will output "yyyy-mm-dd hhmm". Different regional settings will result in different %date% outputs, but you can modify the token order.
If you want a different format, modify the echo statement by rearranging the tokens or using different (or no) separators.
add a comment |
Here's a way to get date time in a single line:
for /f "tokens=2,3,4,5,6 usebackq delims=:/ " %a in ('%date% %time%') do echo %c-%a-%b %d%e
In the US this will output "yyyy-mm-dd hhmm". Different regional settings will result in different %date% outputs, but you can modify the token order.
If you want a different format, modify the echo statement by rearranging the tokens or using different (or no) separators.
add a comment |
Here's a way to get date time in a single line:
for /f "tokens=2,3,4,5,6 usebackq delims=:/ " %a in ('%date% %time%') do echo %c-%a-%b %d%e
In the US this will output "yyyy-mm-dd hhmm". Different regional settings will result in different %date% outputs, but you can modify the token order.
If you want a different format, modify the echo statement by rearranging the tokens or using different (or no) separators.
Here's a way to get date time in a single line:
for /f "tokens=2,3,4,5,6 usebackq delims=:/ " %a in ('%date% %time%') do echo %c-%a-%b %d%e
In the US this will output "yyyy-mm-dd hhmm". Different regional settings will result in different %date% outputs, but you can modify the token order.
If you want a different format, modify the echo statement by rearranging the tokens or using different (or no) separators.
answered Oct 4 '10 at 20:57
Matthew Johnson
9111
9111
add a comment |
add a comment |
Just use this line:
PowerShell -Command "get-date"
add a comment |
Just use this line:
PowerShell -Command "get-date"
add a comment |
Just use this line:
PowerShell -Command "get-date"
Just use this line:
PowerShell -Command "get-date"
answered Nov 19 '14 at 8:51
gdelfino
9,64143540
9,64143540
add a comment |
add a comment |
Short answer :
:: Start - Run , type:
cmd /c "powershell get-date -format ^"{yyyy-MM-dd HH:mm:ss}^"|clip"
:: click into target media, Ctrl + V to paste the result
Long answer
@echo off
:: START USAGE ==================================================================
::SET THE NICETIME
:: SET NICETIME=BOO
:: CALL GetNiceTime.cmd
:: ECHO NICETIME IS %NICETIME%
:: echo nice time is %NICETIME%
:: END USAGE ==================================================================
echo set hhmmsss
:: this is Regional settings dependant so tweak this according your current settings
for /f "tokens=1-3 delims=:" %%a in ('echo %time%') do set hhmmsss=%%a%%b%%c
::DEBUG ECHO hhmmsss IS %hhmmsss%
::DEBUG PAUSE
echo %yyyymmdd%
:: this is Regional settings dependant so tweak this according your current settings
for /f "tokens=1-3 delims=." %%D in ('echo %DATE%') do set yyyymmdd=%%F%%E%%D
::DEBUG ECHO yyyymmdd IS %yyyymmdd%
::DEBUG PAUSE
set NICETIME=%yyyymmdd%_%hhmmsss%
::DEBUG echo THE NICETIME IS %NICETIME%
::DEBUG PAUSE
:: in cmd for /f %i in ('PowerShell -Command "get-date" -format "yyyyMMdd"') do set yyyyMMdd=%i ::in cmd script for /f %%i in ('PowerShell -Command "get-date" -format "yyyyMMdd"') do set yyyyMMdd=%%i
– Yordan Georgiev
Dec 19 '16 at 14:09
add a comment |
Short answer :
:: Start - Run , type:
cmd /c "powershell get-date -format ^"{yyyy-MM-dd HH:mm:ss}^"|clip"
:: click into target media, Ctrl + V to paste the result
Long answer
@echo off
:: START USAGE ==================================================================
::SET THE NICETIME
:: SET NICETIME=BOO
:: CALL GetNiceTime.cmd
:: ECHO NICETIME IS %NICETIME%
:: echo nice time is %NICETIME%
:: END USAGE ==================================================================
echo set hhmmsss
:: this is Regional settings dependant so tweak this according your current settings
for /f "tokens=1-3 delims=:" %%a in ('echo %time%') do set hhmmsss=%%a%%b%%c
::DEBUG ECHO hhmmsss IS %hhmmsss%
::DEBUG PAUSE
echo %yyyymmdd%
:: this is Regional settings dependant so tweak this according your current settings
for /f "tokens=1-3 delims=." %%D in ('echo %DATE%') do set yyyymmdd=%%F%%E%%D
::DEBUG ECHO yyyymmdd IS %yyyymmdd%
::DEBUG PAUSE
set NICETIME=%yyyymmdd%_%hhmmsss%
::DEBUG echo THE NICETIME IS %NICETIME%
::DEBUG PAUSE
:: in cmd for /f %i in ('PowerShell -Command "get-date" -format "yyyyMMdd"') do set yyyyMMdd=%i ::in cmd script for /f %%i in ('PowerShell -Command "get-date" -format "yyyyMMdd"') do set yyyyMMdd=%%i
– Yordan Georgiev
Dec 19 '16 at 14:09
add a comment |
Short answer :
:: Start - Run , type:
cmd /c "powershell get-date -format ^"{yyyy-MM-dd HH:mm:ss}^"|clip"
:: click into target media, Ctrl + V to paste the result
Long answer
@echo off
:: START USAGE ==================================================================
::SET THE NICETIME
:: SET NICETIME=BOO
:: CALL GetNiceTime.cmd
:: ECHO NICETIME IS %NICETIME%
:: echo nice time is %NICETIME%
:: END USAGE ==================================================================
echo set hhmmsss
:: this is Regional settings dependant so tweak this according your current settings
for /f "tokens=1-3 delims=:" %%a in ('echo %time%') do set hhmmsss=%%a%%b%%c
::DEBUG ECHO hhmmsss IS %hhmmsss%
::DEBUG PAUSE
echo %yyyymmdd%
:: this is Regional settings dependant so tweak this according your current settings
for /f "tokens=1-3 delims=." %%D in ('echo %DATE%') do set yyyymmdd=%%F%%E%%D
::DEBUG ECHO yyyymmdd IS %yyyymmdd%
::DEBUG PAUSE
set NICETIME=%yyyymmdd%_%hhmmsss%
::DEBUG echo THE NICETIME IS %NICETIME%
::DEBUG PAUSE
Short answer :
:: Start - Run , type:
cmd /c "powershell get-date -format ^"{yyyy-MM-dd HH:mm:ss}^"|clip"
:: click into target media, Ctrl + V to paste the result
Long answer
@echo off
:: START USAGE ==================================================================
::SET THE NICETIME
:: SET NICETIME=BOO
:: CALL GetNiceTime.cmd
:: ECHO NICETIME IS %NICETIME%
:: echo nice time is %NICETIME%
:: END USAGE ==================================================================
echo set hhmmsss
:: this is Regional settings dependant so tweak this according your current settings
for /f "tokens=1-3 delims=:" %%a in ('echo %time%') do set hhmmsss=%%a%%b%%c
::DEBUG ECHO hhmmsss IS %hhmmsss%
::DEBUG PAUSE
echo %yyyymmdd%
:: this is Regional settings dependant so tweak this according your current settings
for /f "tokens=1-3 delims=." %%D in ('echo %DATE%') do set yyyymmdd=%%F%%E%%D
::DEBUG ECHO yyyymmdd IS %yyyymmdd%
::DEBUG PAUSE
set NICETIME=%yyyymmdd%_%hhmmsss%
::DEBUG echo THE NICETIME IS %NICETIME%
::DEBUG PAUSE
edited Feb 28 at 12:32
answered May 18 '10 at 6:03
Yordan Georgiev
2,51812839
2,51812839
:: in cmd for /f %i in ('PowerShell -Command "get-date" -format "yyyyMMdd"') do set yyyyMMdd=%i ::in cmd script for /f %%i in ('PowerShell -Command "get-date" -format "yyyyMMdd"') do set yyyyMMdd=%%i
– Yordan Georgiev
Dec 19 '16 at 14:09
add a comment |
:: in cmd for /f %i in ('PowerShell -Command "get-date" -format "yyyyMMdd"') do set yyyyMMdd=%i ::in cmd script for /f %%i in ('PowerShell -Command "get-date" -format "yyyyMMdd"') do set yyyyMMdd=%%i
– Yordan Georgiev
Dec 19 '16 at 14:09
:: in cmd for /f %i in ('PowerShell -Command "get-date" -format "yyyyMMdd"') do set yyyyMMdd=%i ::in cmd script for /f %%i in ('PowerShell -Command "get-date" -format "yyyyMMdd"') do set yyyyMMdd=%%i
– Yordan Georgiev
Dec 19 '16 at 14:09
:: in cmd for /f %i in ('PowerShell -Command "get-date" -format "yyyyMMdd"') do set yyyyMMdd=%i ::in cmd script for /f %%i in ('PowerShell -Command "get-date" -format "yyyyMMdd"') do set yyyyMMdd=%%i
– Yordan Georgiev
Dec 19 '16 at 14:09
add a comment |
And here is a similar batch-file for the time portion.
:: http://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi
:: Works on any NT/2k machine independent of regional time settings
::
:: Gets the time in ISO 8601 24-hour format
::
:: Note that %time% gets you fractions of seconds, and time /t doesn't, but gets you AM/PM if your locale supports that.
:: Since ISO 8601 does not care about AM/PM, we use %time%
::
@ECHO off
SETLOCAL ENABLEEXTENSIONS
for /f "tokens=1-4 delims=:,.-/ " %%i in ('echo %time%') do (
set 'hh'=%%i
set 'mm'=%%j
set 'ss'=%%k
set 'ff'=%%l)
ENDLOCAL & SET v_Hour=%'hh'%& SET v_Minute=%'mm'%& SET v_Second=%'ss'%& SET v_Fraction=%'ff'%
ECHO Now is Hour: [%V_Hour%] Minute: [%V_Minute%] Second: [%v_Second%] Fraction: [%v_Fraction%]
set timestring=%V_Hour%%V_Minute%%v_Second%.%v_Fraction%
echo %timestring%
:EOF
--jeroen
Hi, I was able to load files according to Modified date using a command below,z: & forfiles /m *.jpg /s /d 07/16/2015 /c “cmd /c echo @fdate @ftime @path”
But I wanna know how to load files according to Created date. Any help would be very appreciated. A question’s been asked on stackoverflow but no answer yet. Please take a look at the link for the details stackoverflow.com/q/32293517/3327081
– kolunar
Sep 2 '15 at 13:35
1
Ask a new question about that. I've never usedforfiles
.
– Jeroen Wiert Pluimers
Sep 4 '15 at 11:09
add a comment |
And here is a similar batch-file for the time portion.
:: http://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi
:: Works on any NT/2k machine independent of regional time settings
::
:: Gets the time in ISO 8601 24-hour format
::
:: Note that %time% gets you fractions of seconds, and time /t doesn't, but gets you AM/PM if your locale supports that.
:: Since ISO 8601 does not care about AM/PM, we use %time%
::
@ECHO off
SETLOCAL ENABLEEXTENSIONS
for /f "tokens=1-4 delims=:,.-/ " %%i in ('echo %time%') do (
set 'hh'=%%i
set 'mm'=%%j
set 'ss'=%%k
set 'ff'=%%l)
ENDLOCAL & SET v_Hour=%'hh'%& SET v_Minute=%'mm'%& SET v_Second=%'ss'%& SET v_Fraction=%'ff'%
ECHO Now is Hour: [%V_Hour%] Minute: [%V_Minute%] Second: [%v_Second%] Fraction: [%v_Fraction%]
set timestring=%V_Hour%%V_Minute%%v_Second%.%v_Fraction%
echo %timestring%
:EOF
--jeroen
Hi, I was able to load files according to Modified date using a command below,z: & forfiles /m *.jpg /s /d 07/16/2015 /c “cmd /c echo @fdate @ftime @path”
But I wanna know how to load files according to Created date. Any help would be very appreciated. A question’s been asked on stackoverflow but no answer yet. Please take a look at the link for the details stackoverflow.com/q/32293517/3327081
– kolunar
Sep 2 '15 at 13:35
1
Ask a new question about that. I've never usedforfiles
.
– Jeroen Wiert Pluimers
Sep 4 '15 at 11:09
add a comment |
And here is a similar batch-file for the time portion.
:: http://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi
:: Works on any NT/2k machine independent of regional time settings
::
:: Gets the time in ISO 8601 24-hour format
::
:: Note that %time% gets you fractions of seconds, and time /t doesn't, but gets you AM/PM if your locale supports that.
:: Since ISO 8601 does not care about AM/PM, we use %time%
::
@ECHO off
SETLOCAL ENABLEEXTENSIONS
for /f "tokens=1-4 delims=:,.-/ " %%i in ('echo %time%') do (
set 'hh'=%%i
set 'mm'=%%j
set 'ss'=%%k
set 'ff'=%%l)
ENDLOCAL & SET v_Hour=%'hh'%& SET v_Minute=%'mm'%& SET v_Second=%'ss'%& SET v_Fraction=%'ff'%
ECHO Now is Hour: [%V_Hour%] Minute: [%V_Minute%] Second: [%v_Second%] Fraction: [%v_Fraction%]
set timestring=%V_Hour%%V_Minute%%v_Second%.%v_Fraction%
echo %timestring%
:EOF
--jeroen
And here is a similar batch-file for the time portion.
:: http://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi
:: Works on any NT/2k machine independent of regional time settings
::
:: Gets the time in ISO 8601 24-hour format
::
:: Note that %time% gets you fractions of seconds, and time /t doesn't, but gets you AM/PM if your locale supports that.
:: Since ISO 8601 does not care about AM/PM, we use %time%
::
@ECHO off
SETLOCAL ENABLEEXTENSIONS
for /f "tokens=1-4 delims=:,.-/ " %%i in ('echo %time%') do (
set 'hh'=%%i
set 'mm'=%%j
set 'ss'=%%k
set 'ff'=%%l)
ENDLOCAL & SET v_Hour=%'hh'%& SET v_Minute=%'mm'%& SET v_Second=%'ss'%& SET v_Fraction=%'ff'%
ECHO Now is Hour: [%V_Hour%] Minute: [%V_Minute%] Second: [%v_Second%] Fraction: [%v_Fraction%]
set timestring=%V_Hour%%V_Minute%%v_Second%.%v_Fraction%
echo %timestring%
:EOF
--jeroen
answered Jan 3 '11 at 13:26
Jeroen Wiert Pluimers
20.6k552129
20.6k552129
Hi, I was able to load files according to Modified date using a command below,z: & forfiles /m *.jpg /s /d 07/16/2015 /c “cmd /c echo @fdate @ftime @path”
But I wanna know how to load files according to Created date. Any help would be very appreciated. A question’s been asked on stackoverflow but no answer yet. Please take a look at the link for the details stackoverflow.com/q/32293517/3327081
– kolunar
Sep 2 '15 at 13:35
1
Ask a new question about that. I've never usedforfiles
.
– Jeroen Wiert Pluimers
Sep 4 '15 at 11:09
add a comment |
Hi, I was able to load files according to Modified date using a command below,z: & forfiles /m *.jpg /s /d 07/16/2015 /c “cmd /c echo @fdate @ftime @path”
But I wanna know how to load files according to Created date. Any help would be very appreciated. A question’s been asked on stackoverflow but no answer yet. Please take a look at the link for the details stackoverflow.com/q/32293517/3327081
– kolunar
Sep 2 '15 at 13:35
1
Ask a new question about that. I've never usedforfiles
.
– Jeroen Wiert Pluimers
Sep 4 '15 at 11:09
Hi, I was able to load files according to Modified date using a command below,
z: & forfiles /m *.jpg /s /d 07/16/2015 /c “cmd /c echo @fdate @ftime @path”
But I wanna know how to load files according to Created date. Any help would be very appreciated. A question’s been asked on stackoverflow but no answer yet. Please take a look at the link for the details stackoverflow.com/q/32293517/3327081– kolunar
Sep 2 '15 at 13:35
Hi, I was able to load files according to Modified date using a command below,
z: & forfiles /m *.jpg /s /d 07/16/2015 /c “cmd /c echo @fdate @ftime @path”
But I wanna know how to load files according to Created date. Any help would be very appreciated. A question’s been asked on stackoverflow but no answer yet. Please take a look at the link for the details stackoverflow.com/q/32293517/3327081– kolunar
Sep 2 '15 at 13:35
1
1
Ask a new question about that. I've never used
forfiles
.– Jeroen Wiert Pluimers
Sep 4 '15 at 11:09
Ask a new question about that. I've never used
forfiles
.– Jeroen Wiert Pluimers
Sep 4 '15 at 11:09
add a comment |
I changed the answer with the batch file from vMax so it works with the Dutch language too.
The Dutch - persistent as we are - have a few changes in the %date%
, date/t
, and date
that break the original batch-file.
It would be nice if some people can check this against other Windows locales as well, and report back the results.
If the batch-file fails at your location, then please include the output of these two statements on the command prompt:echo:^|date
date/t
This is a sample of the output you should get from the batch-file:
C:temp>set-date-cmd.bat
Today is Year: [2011] Month: [01] Day: [03]
20110103
Here is the revised code with comments on why:
:: https://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi
:: Works on any NT/2k machine independent of regional date settings
::
:: 20110103 - adapted by jeroen@pluimers.com for Dutch locale
:: Dutch will get jj as year from echo:^|date, so the '%%c' trick does not work as it will fill 'jj', but we want 'yy'
:: luckily, all countries seem to have year at the end: http://en.wikipedia.org/wiki/Calendar_date
:: set '%%c'=%%k
:: set 'yy'=%%k
::
:: In addition, date will display the current date before the input prompt using dashes
:: in Dutch, but using slashes in English, so there will be two occurances of the outer loop in Dutch
:: and one occurence in English.
:: This skips the first iteration:
:: if "%%a" GEQ "A"
::
:: echo:^|date
:: Huidige datum: ma 03-01-2011
:: Voer de nieuwe datum in: (dd-mm-jj)
:: The current date is: Mon 01/03/2011
:: Enter the new date: (mm-dd-yy)
::
:: date/t
:: ma 03-01-2011
:: Mon 01/03/2011
::
:: The assumption in this batch-file is that echo:^|date will return the date format
:: using either mm and dd or dd and mm in the first two valid tokens on the second line, and the year as the last token.
::
:: The outer loop will get the right tokens, the inner loop assigns the variables depending on the tokens.
:: That will resolve the order of the tokens.
::
@ECHO off
set v_day=
set v_month=
set v_year=
SETLOCAL ENABLEEXTENSIONS
if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
::DEBUG echo toks=%toks%
for /f "tokens=2-4 delims=(-)" %%a in ('echo:^|date') do (
::DEBUG echo first token=%%a
if "%%a" GEQ "A" (
for /f "tokens=%toks% delims=.-/ " %%i in ('date/t') do (
set '%%a'=%%i
set '%%b'=%%j
set 'yy'=%%k
)
)
)
if %'yy'% LSS 100 set 'yy'=20%'yy'%
set Today=%'yy'%-%'mm'%-%'dd'%
ENDLOCAL & SET v_year=%'yy'%& SET v_month=%'mm'%& SET v_day=%'dd'%
ECHO Today is Year: [%V_Year%] Month: [%V_Month%] Day: [%V_Day%]
set datestring=%V_Year%%V_Month%%V_Day%
echo %datestring%
:EOF
--jeroen
2
Some do use years first, or lack leading zeroes; see Wikipedia's Date format by country. The French might usejj-mm-aaaa
for jour, mois, annee? Italians maybegg/mm/aaaa
for giorno, mese, anno? Germanstt.mm.jjjj
for Tag, Monat, Jahr? But then: I guess in most countries only a few languages are used. Like in The Netherlands indeed Windows will often be English or Dutch, not much else. Good enough for me.
– Arjan
Jun 23 '12 at 9:49
2
As an aside: another version in Hidden features of Windows batch files is less perfect (needs the fix for the Dutchjj
, and does not enforce a 4 digit year), but usesshift
to discard the day likeMon
orma
. Just different.
– Arjan
Jun 23 '12 at 9:50
3
It breaks on a German system. Year and month work, but day fails because "day" starts with a "T" in German ("Tag"), not a "d". The format string in the prompt is(TT-MM-JJ)
, thedate/t
output is23.06.2012
. /cc @Arjan
– balpha♦
Jun 23 '12 at 10:18
2
Another aside: one could also get the order from the registry, usingreg query "HKCUControl PanelInternational" /vShortDate
. Beware while testing: for an open command prompt, changing that Control Panel setting also changes the format used to display the date (for bothdate
anddate /t
andecho %date%
), but on Windows 7 does NOT change the format for the new date! Like changing my short date format intoYY/MM/dd
, gets me:The current date is: 12/06/23 Enter the new date: (mm-dd-yy)
. Opening a new command prompt fixes that.
– Arjan
Jun 23 '12 at 10:38
2
@Arjan this should bereg query "HKCUControl PanelInternational" /v sShortDate
.
– tricasse
Nov 19 '15 at 13:31
|
show 2 more comments
I changed the answer with the batch file from vMax so it works with the Dutch language too.
The Dutch - persistent as we are - have a few changes in the %date%
, date/t
, and date
that break the original batch-file.
It would be nice if some people can check this against other Windows locales as well, and report back the results.
If the batch-file fails at your location, then please include the output of these two statements on the command prompt:echo:^|date
date/t
This is a sample of the output you should get from the batch-file:
C:temp>set-date-cmd.bat
Today is Year: [2011] Month: [01] Day: [03]
20110103
Here is the revised code with comments on why:
:: https://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi
:: Works on any NT/2k machine independent of regional date settings
::
:: 20110103 - adapted by jeroen@pluimers.com for Dutch locale
:: Dutch will get jj as year from echo:^|date, so the '%%c' trick does not work as it will fill 'jj', but we want 'yy'
:: luckily, all countries seem to have year at the end: http://en.wikipedia.org/wiki/Calendar_date
:: set '%%c'=%%k
:: set 'yy'=%%k
::
:: In addition, date will display the current date before the input prompt using dashes
:: in Dutch, but using slashes in English, so there will be two occurances of the outer loop in Dutch
:: and one occurence in English.
:: This skips the first iteration:
:: if "%%a" GEQ "A"
::
:: echo:^|date
:: Huidige datum: ma 03-01-2011
:: Voer de nieuwe datum in: (dd-mm-jj)
:: The current date is: Mon 01/03/2011
:: Enter the new date: (mm-dd-yy)
::
:: date/t
:: ma 03-01-2011
:: Mon 01/03/2011
::
:: The assumption in this batch-file is that echo:^|date will return the date format
:: using either mm and dd or dd and mm in the first two valid tokens on the second line, and the year as the last token.
::
:: The outer loop will get the right tokens, the inner loop assigns the variables depending on the tokens.
:: That will resolve the order of the tokens.
::
@ECHO off
set v_day=
set v_month=
set v_year=
SETLOCAL ENABLEEXTENSIONS
if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
::DEBUG echo toks=%toks%
for /f "tokens=2-4 delims=(-)" %%a in ('echo:^|date') do (
::DEBUG echo first token=%%a
if "%%a" GEQ "A" (
for /f "tokens=%toks% delims=.-/ " %%i in ('date/t') do (
set '%%a'=%%i
set '%%b'=%%j
set 'yy'=%%k
)
)
)
if %'yy'% LSS 100 set 'yy'=20%'yy'%
set Today=%'yy'%-%'mm'%-%'dd'%
ENDLOCAL & SET v_year=%'yy'%& SET v_month=%'mm'%& SET v_day=%'dd'%
ECHO Today is Year: [%V_Year%] Month: [%V_Month%] Day: [%V_Day%]
set datestring=%V_Year%%V_Month%%V_Day%
echo %datestring%
:EOF
--jeroen
2
Some do use years first, or lack leading zeroes; see Wikipedia's Date format by country. The French might usejj-mm-aaaa
for jour, mois, annee? Italians maybegg/mm/aaaa
for giorno, mese, anno? Germanstt.mm.jjjj
for Tag, Monat, Jahr? But then: I guess in most countries only a few languages are used. Like in The Netherlands indeed Windows will often be English or Dutch, not much else. Good enough for me.
– Arjan
Jun 23 '12 at 9:49
2
As an aside: another version in Hidden features of Windows batch files is less perfect (needs the fix for the Dutchjj
, and does not enforce a 4 digit year), but usesshift
to discard the day likeMon
orma
. Just different.
– Arjan
Jun 23 '12 at 9:50
3
It breaks on a German system. Year and month work, but day fails because "day" starts with a "T" in German ("Tag"), not a "d". The format string in the prompt is(TT-MM-JJ)
, thedate/t
output is23.06.2012
. /cc @Arjan
– balpha♦
Jun 23 '12 at 10:18
2
Another aside: one could also get the order from the registry, usingreg query "HKCUControl PanelInternational" /vShortDate
. Beware while testing: for an open command prompt, changing that Control Panel setting also changes the format used to display the date (for bothdate
anddate /t
andecho %date%
), but on Windows 7 does NOT change the format for the new date! Like changing my short date format intoYY/MM/dd
, gets me:The current date is: 12/06/23 Enter the new date: (mm-dd-yy)
. Opening a new command prompt fixes that.
– Arjan
Jun 23 '12 at 10:38
2
@Arjan this should bereg query "HKCUControl PanelInternational" /v sShortDate
.
– tricasse
Nov 19 '15 at 13:31
|
show 2 more comments
I changed the answer with the batch file from vMax so it works with the Dutch language too.
The Dutch - persistent as we are - have a few changes in the %date%
, date/t
, and date
that break the original batch-file.
It would be nice if some people can check this against other Windows locales as well, and report back the results.
If the batch-file fails at your location, then please include the output of these two statements on the command prompt:echo:^|date
date/t
This is a sample of the output you should get from the batch-file:
C:temp>set-date-cmd.bat
Today is Year: [2011] Month: [01] Day: [03]
20110103
Here is the revised code with comments on why:
:: https://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi
:: Works on any NT/2k machine independent of regional date settings
::
:: 20110103 - adapted by jeroen@pluimers.com for Dutch locale
:: Dutch will get jj as year from echo:^|date, so the '%%c' trick does not work as it will fill 'jj', but we want 'yy'
:: luckily, all countries seem to have year at the end: http://en.wikipedia.org/wiki/Calendar_date
:: set '%%c'=%%k
:: set 'yy'=%%k
::
:: In addition, date will display the current date before the input prompt using dashes
:: in Dutch, but using slashes in English, so there will be two occurances of the outer loop in Dutch
:: and one occurence in English.
:: This skips the first iteration:
:: if "%%a" GEQ "A"
::
:: echo:^|date
:: Huidige datum: ma 03-01-2011
:: Voer de nieuwe datum in: (dd-mm-jj)
:: The current date is: Mon 01/03/2011
:: Enter the new date: (mm-dd-yy)
::
:: date/t
:: ma 03-01-2011
:: Mon 01/03/2011
::
:: The assumption in this batch-file is that echo:^|date will return the date format
:: using either mm and dd or dd and mm in the first two valid tokens on the second line, and the year as the last token.
::
:: The outer loop will get the right tokens, the inner loop assigns the variables depending on the tokens.
:: That will resolve the order of the tokens.
::
@ECHO off
set v_day=
set v_month=
set v_year=
SETLOCAL ENABLEEXTENSIONS
if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
::DEBUG echo toks=%toks%
for /f "tokens=2-4 delims=(-)" %%a in ('echo:^|date') do (
::DEBUG echo first token=%%a
if "%%a" GEQ "A" (
for /f "tokens=%toks% delims=.-/ " %%i in ('date/t') do (
set '%%a'=%%i
set '%%b'=%%j
set 'yy'=%%k
)
)
)
if %'yy'% LSS 100 set 'yy'=20%'yy'%
set Today=%'yy'%-%'mm'%-%'dd'%
ENDLOCAL & SET v_year=%'yy'%& SET v_month=%'mm'%& SET v_day=%'dd'%
ECHO Today is Year: [%V_Year%] Month: [%V_Month%] Day: [%V_Day%]
set datestring=%V_Year%%V_Month%%V_Day%
echo %datestring%
:EOF
--jeroen
I changed the answer with the batch file from vMax so it works with the Dutch language too.
The Dutch - persistent as we are - have a few changes in the %date%
, date/t
, and date
that break the original batch-file.
It would be nice if some people can check this against other Windows locales as well, and report back the results.
If the batch-file fails at your location, then please include the output of these two statements on the command prompt:echo:^|date
date/t
This is a sample of the output you should get from the batch-file:
C:temp>set-date-cmd.bat
Today is Year: [2011] Month: [01] Day: [03]
20110103
Here is the revised code with comments on why:
:: https://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi
:: Works on any NT/2k machine independent of regional date settings
::
:: 20110103 - adapted by jeroen@pluimers.com for Dutch locale
:: Dutch will get jj as year from echo:^|date, so the '%%c' trick does not work as it will fill 'jj', but we want 'yy'
:: luckily, all countries seem to have year at the end: http://en.wikipedia.org/wiki/Calendar_date
:: set '%%c'=%%k
:: set 'yy'=%%k
::
:: In addition, date will display the current date before the input prompt using dashes
:: in Dutch, but using slashes in English, so there will be two occurances of the outer loop in Dutch
:: and one occurence in English.
:: This skips the first iteration:
:: if "%%a" GEQ "A"
::
:: echo:^|date
:: Huidige datum: ma 03-01-2011
:: Voer de nieuwe datum in: (dd-mm-jj)
:: The current date is: Mon 01/03/2011
:: Enter the new date: (mm-dd-yy)
::
:: date/t
:: ma 03-01-2011
:: Mon 01/03/2011
::
:: The assumption in this batch-file is that echo:^|date will return the date format
:: using either mm and dd or dd and mm in the first two valid tokens on the second line, and the year as the last token.
::
:: The outer loop will get the right tokens, the inner loop assigns the variables depending on the tokens.
:: That will resolve the order of the tokens.
::
@ECHO off
set v_day=
set v_month=
set v_year=
SETLOCAL ENABLEEXTENSIONS
if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
::DEBUG echo toks=%toks%
for /f "tokens=2-4 delims=(-)" %%a in ('echo:^|date') do (
::DEBUG echo first token=%%a
if "%%a" GEQ "A" (
for /f "tokens=%toks% delims=.-/ " %%i in ('date/t') do (
set '%%a'=%%i
set '%%b'=%%j
set 'yy'=%%k
)
)
)
if %'yy'% LSS 100 set 'yy'=20%'yy'%
set Today=%'yy'%-%'mm'%-%'dd'%
ENDLOCAL & SET v_year=%'yy'%& SET v_month=%'mm'%& SET v_day=%'dd'%
ECHO Today is Year: [%V_Year%] Month: [%V_Month%] Day: [%V_Day%]
set datestring=%V_Year%%V_Month%%V_Day%
echo %datestring%
:EOF
--jeroen
edited May 23 '17 at 12:18
Community♦
11
11
answered Jan 3 '11 at 12:55
Jeroen Wiert Pluimers
20.6k552129
20.6k552129
2
Some do use years first, or lack leading zeroes; see Wikipedia's Date format by country. The French might usejj-mm-aaaa
for jour, mois, annee? Italians maybegg/mm/aaaa
for giorno, mese, anno? Germanstt.mm.jjjj
for Tag, Monat, Jahr? But then: I guess in most countries only a few languages are used. Like in The Netherlands indeed Windows will often be English or Dutch, not much else. Good enough for me.
– Arjan
Jun 23 '12 at 9:49
2
As an aside: another version in Hidden features of Windows batch files is less perfect (needs the fix for the Dutchjj
, and does not enforce a 4 digit year), but usesshift
to discard the day likeMon
orma
. Just different.
– Arjan
Jun 23 '12 at 9:50
3
It breaks on a German system. Year and month work, but day fails because "day" starts with a "T" in German ("Tag"), not a "d". The format string in the prompt is(TT-MM-JJ)
, thedate/t
output is23.06.2012
. /cc @Arjan
– balpha♦
Jun 23 '12 at 10:18
2
Another aside: one could also get the order from the registry, usingreg query "HKCUControl PanelInternational" /vShortDate
. Beware while testing: for an open command prompt, changing that Control Panel setting also changes the format used to display the date (for bothdate
anddate /t
andecho %date%
), but on Windows 7 does NOT change the format for the new date! Like changing my short date format intoYY/MM/dd
, gets me:The current date is: 12/06/23 Enter the new date: (mm-dd-yy)
. Opening a new command prompt fixes that.
– Arjan
Jun 23 '12 at 10:38
2
@Arjan this should bereg query "HKCUControl PanelInternational" /v sShortDate
.
– tricasse
Nov 19 '15 at 13:31
|
show 2 more comments
2
Some do use years first, or lack leading zeroes; see Wikipedia's Date format by country. The French might usejj-mm-aaaa
for jour, mois, annee? Italians maybegg/mm/aaaa
for giorno, mese, anno? Germanstt.mm.jjjj
for Tag, Monat, Jahr? But then: I guess in most countries only a few languages are used. Like in The Netherlands indeed Windows will often be English or Dutch, not much else. Good enough for me.
– Arjan
Jun 23 '12 at 9:49
2
As an aside: another version in Hidden features of Windows batch files is less perfect (needs the fix for the Dutchjj
, and does not enforce a 4 digit year), but usesshift
to discard the day likeMon
orma
. Just different.
– Arjan
Jun 23 '12 at 9:50
3
It breaks on a German system. Year and month work, but day fails because "day" starts with a "T" in German ("Tag"), not a "d". The format string in the prompt is(TT-MM-JJ)
, thedate/t
output is23.06.2012
. /cc @Arjan
– balpha♦
Jun 23 '12 at 10:18
2
Another aside: one could also get the order from the registry, usingreg query "HKCUControl PanelInternational" /vShortDate
. Beware while testing: for an open command prompt, changing that Control Panel setting also changes the format used to display the date (for bothdate
anddate /t
andecho %date%
), but on Windows 7 does NOT change the format for the new date! Like changing my short date format intoYY/MM/dd
, gets me:The current date is: 12/06/23 Enter the new date: (mm-dd-yy)
. Opening a new command prompt fixes that.
– Arjan
Jun 23 '12 at 10:38
2
@Arjan this should bereg query "HKCUControl PanelInternational" /v sShortDate
.
– tricasse
Nov 19 '15 at 13:31
2
2
Some do use years first, or lack leading zeroes; see Wikipedia's Date format by country. The French might use
jj-mm-aaaa
for jour, mois, annee? Italians maybe gg/mm/aaaa
for giorno, mese, anno? Germans tt.mm.jjjj
for Tag, Monat, Jahr? But then: I guess in most countries only a few languages are used. Like in The Netherlands indeed Windows will often be English or Dutch, not much else. Good enough for me.– Arjan
Jun 23 '12 at 9:49
Some do use years first, or lack leading zeroes; see Wikipedia's Date format by country. The French might use
jj-mm-aaaa
for jour, mois, annee? Italians maybe gg/mm/aaaa
for giorno, mese, anno? Germans tt.mm.jjjj
for Tag, Monat, Jahr? But then: I guess in most countries only a few languages are used. Like in The Netherlands indeed Windows will often be English or Dutch, not much else. Good enough for me.– Arjan
Jun 23 '12 at 9:49
2
2
As an aside: another version in Hidden features of Windows batch files is less perfect (needs the fix for the Dutch
jj
, and does not enforce a 4 digit year), but uses shift
to discard the day like Mon
or ma
. Just different.– Arjan
Jun 23 '12 at 9:50
As an aside: another version in Hidden features of Windows batch files is less perfect (needs the fix for the Dutch
jj
, and does not enforce a 4 digit year), but uses shift
to discard the day like Mon
or ma
. Just different.– Arjan
Jun 23 '12 at 9:50
3
3
It breaks on a German system. Year and month work, but day fails because "day" starts with a "T" in German ("Tag"), not a "d". The format string in the prompt is
(TT-MM-JJ)
, the date/t
output is 23.06.2012
. /cc @Arjan– balpha♦
Jun 23 '12 at 10:18
It breaks on a German system. Year and month work, but day fails because "day" starts with a "T" in German ("Tag"), not a "d". The format string in the prompt is
(TT-MM-JJ)
, the date/t
output is 23.06.2012
. /cc @Arjan– balpha♦
Jun 23 '12 at 10:18
2
2
Another aside: one could also get the order from the registry, using
reg query "HKCUControl PanelInternational" /vShortDate
. Beware while testing: for an open command prompt, changing that Control Panel setting also changes the format used to display the date (for both date
and date /t
and echo %date%
), but on Windows 7 does NOT change the format for the new date! Like changing my short date format into YY/MM/dd
, gets me: The current date is: 12/06/23 Enter the new date: (mm-dd-yy)
. Opening a new command prompt fixes that.– Arjan
Jun 23 '12 at 10:38
Another aside: one could also get the order from the registry, using
reg query "HKCUControl PanelInternational" /vShortDate
. Beware while testing: for an open command prompt, changing that Control Panel setting also changes the format used to display the date (for both date
and date /t
and echo %date%
), but on Windows 7 does NOT change the format for the new date! Like changing my short date format into YY/MM/dd
, gets me: The current date is: 12/06/23 Enter the new date: (mm-dd-yy)
. Opening a new command prompt fixes that.– Arjan
Jun 23 '12 at 10:38
2
2
@Arjan this should be
reg query "HKCUControl PanelInternational" /v sShortDate
.– tricasse
Nov 19 '15 at 13:31
@Arjan this should be
reg query "HKCUControl PanelInternational" /v sShortDate
.– tricasse
Nov 19 '15 at 13:31
|
show 2 more comments
Matthew Johnson's one-liner solution to get the one-liner date and time is eloquent and useful.
It does however need a simple modification to work from within a batch file:
for /f "tokens=2,3,4,5,6 usebackq delims=:/ " %%a in ('%date% %time%') do echo %%c-%%a-%%b %%d%%e
Does not work in CMD (%%a was unexpected at this time) or in PowerShell (Missing opening '(' after keyword for) on Windows 8.1
– rainabba
Jan 28 '14 at 16:28
3
Rainabba, that is exactly the error you get when that command is issued from the CMD line. However, "from within a batch file", the command returns "2014-01-30 1324".
– John Langstaff
Jan 30 '14 at 18:30
add a comment |
Matthew Johnson's one-liner solution to get the one-liner date and time is eloquent and useful.
It does however need a simple modification to work from within a batch file:
for /f "tokens=2,3,4,5,6 usebackq delims=:/ " %%a in ('%date% %time%') do echo %%c-%%a-%%b %%d%%e
Does not work in CMD (%%a was unexpected at this time) or in PowerShell (Missing opening '(' after keyword for) on Windows 8.1
– rainabba
Jan 28 '14 at 16:28
3
Rainabba, that is exactly the error you get when that command is issued from the CMD line. However, "from within a batch file", the command returns "2014-01-30 1324".
– John Langstaff
Jan 30 '14 at 18:30
add a comment |
Matthew Johnson's one-liner solution to get the one-liner date and time is eloquent and useful.
It does however need a simple modification to work from within a batch file:
for /f "tokens=2,3,4,5,6 usebackq delims=:/ " %%a in ('%date% %time%') do echo %%c-%%a-%%b %%d%%e
Matthew Johnson's one-liner solution to get the one-liner date and time is eloquent and useful.
It does however need a simple modification to work from within a batch file:
for /f "tokens=2,3,4,5,6 usebackq delims=:/ " %%a in ('%date% %time%') do echo %%c-%%a-%%b %%d%%e
edited Sep 14 at 13:00
JonathanDavidArndt
1,55372333
1,55372333
answered Apr 28 '13 at 16:05
John Langstaff
81089
81089
Does not work in CMD (%%a was unexpected at this time) or in PowerShell (Missing opening '(' after keyword for) on Windows 8.1
– rainabba
Jan 28 '14 at 16:28
3
Rainabba, that is exactly the error you get when that command is issued from the CMD line. However, "from within a batch file", the command returns "2014-01-30 1324".
– John Langstaff
Jan 30 '14 at 18:30
add a comment |
Does not work in CMD (%%a was unexpected at this time) or in PowerShell (Missing opening '(' after keyword for) on Windows 8.1
– rainabba
Jan 28 '14 at 16:28
3
Rainabba, that is exactly the error you get when that command is issued from the CMD line. However, "from within a batch file", the command returns "2014-01-30 1324".
– John Langstaff
Jan 30 '14 at 18:30
Does not work in CMD (%%a was unexpected at this time) or in PowerShell (Missing opening '(' after keyword for) on Windows 8.1
– rainabba
Jan 28 '14 at 16:28
Does not work in CMD (%%a was unexpected at this time) or in PowerShell (Missing opening '(' after keyword for) on Windows 8.1
– rainabba
Jan 28 '14 at 16:28
3
3
Rainabba, that is exactly the error you get when that command is issued from the CMD line. However, "from within a batch file", the command returns "2014-01-30 1324".
– John Langstaff
Jan 30 '14 at 18:30
Rainabba, that is exactly the error you get when that command is issued from the CMD line. However, "from within a batch file", the command returns "2014-01-30 1324".
– John Langstaff
Jan 30 '14 at 18:30
add a comment |
A function that is based on wmic
:
:Now -- Gets the current date and time into separate variables
:: %~1: [out] Year
:: %~2: [out] Month
:: %~3: [out] Day
:: %~4: [out] Hour
:: %~5: [out] Minute
:: %~6: [out] Second
setlocal
for /f %%t in ('wmic os get LocalDateTime ^| findstr /b [0-9]') do set T=%%t
endlocal & (
if "%~1" neq "" set %~1=%T:~0,4%
if "%~2" neq "" set %~2=%T:~4,2%
if "%~3" neq "" set %~3=%T:~6,2%
if "%~4" neq "" set %~4=%T:~8,2%
if "%~5" neq "" set %~5=%T:~10,2%
if "%~6" neq "" set %~6=%T:~12,2%
)
goto:eof
Upside: Region independent. Downside: Only system administrators can run wmic.exe.
Usage:
call:Now Y M D H N S
echo %Y%-%M%-%D% %H%:%N%:%S%
This echos a string like this:
2014-01-22 12:51:53
Note that function parameters are out-Parameters - that is, you must supply variable names instead of values.
All parameters are optional, so call:Now Y M
is a valid call if you only want to get year and month.
add a comment |
A function that is based on wmic
:
:Now -- Gets the current date and time into separate variables
:: %~1: [out] Year
:: %~2: [out] Month
:: %~3: [out] Day
:: %~4: [out] Hour
:: %~5: [out] Minute
:: %~6: [out] Second
setlocal
for /f %%t in ('wmic os get LocalDateTime ^| findstr /b [0-9]') do set T=%%t
endlocal & (
if "%~1" neq "" set %~1=%T:~0,4%
if "%~2" neq "" set %~2=%T:~4,2%
if "%~3" neq "" set %~3=%T:~6,2%
if "%~4" neq "" set %~4=%T:~8,2%
if "%~5" neq "" set %~5=%T:~10,2%
if "%~6" neq "" set %~6=%T:~12,2%
)
goto:eof
Upside: Region independent. Downside: Only system administrators can run wmic.exe.
Usage:
call:Now Y M D H N S
echo %Y%-%M%-%D% %H%:%N%:%S%
This echos a string like this:
2014-01-22 12:51:53
Note that function parameters are out-Parameters - that is, you must supply variable names instead of values.
All parameters are optional, so call:Now Y M
is a valid call if you only want to get year and month.
add a comment |
A function that is based on wmic
:
:Now -- Gets the current date and time into separate variables
:: %~1: [out] Year
:: %~2: [out] Month
:: %~3: [out] Day
:: %~4: [out] Hour
:: %~5: [out] Minute
:: %~6: [out] Second
setlocal
for /f %%t in ('wmic os get LocalDateTime ^| findstr /b [0-9]') do set T=%%t
endlocal & (
if "%~1" neq "" set %~1=%T:~0,4%
if "%~2" neq "" set %~2=%T:~4,2%
if "%~3" neq "" set %~3=%T:~6,2%
if "%~4" neq "" set %~4=%T:~8,2%
if "%~5" neq "" set %~5=%T:~10,2%
if "%~6" neq "" set %~6=%T:~12,2%
)
goto:eof
Upside: Region independent. Downside: Only system administrators can run wmic.exe.
Usage:
call:Now Y M D H N S
echo %Y%-%M%-%D% %H%:%N%:%S%
This echos a string like this:
2014-01-22 12:51:53
Note that function parameters are out-Parameters - that is, you must supply variable names instead of values.
All parameters are optional, so call:Now Y M
is a valid call if you only want to get year and month.
A function that is based on wmic
:
:Now -- Gets the current date and time into separate variables
:: %~1: [out] Year
:: %~2: [out] Month
:: %~3: [out] Day
:: %~4: [out] Hour
:: %~5: [out] Minute
:: %~6: [out] Second
setlocal
for /f %%t in ('wmic os get LocalDateTime ^| findstr /b [0-9]') do set T=%%t
endlocal & (
if "%~1" neq "" set %~1=%T:~0,4%
if "%~2" neq "" set %~2=%T:~4,2%
if "%~3" neq "" set %~3=%T:~6,2%
if "%~4" neq "" set %~4=%T:~8,2%
if "%~5" neq "" set %~5=%T:~10,2%
if "%~6" neq "" set %~6=%T:~12,2%
)
goto:eof
Upside: Region independent. Downside: Only system administrators can run wmic.exe.
Usage:
call:Now Y M D H N S
echo %Y%-%M%-%D% %H%:%N%:%S%
This echos a string like this:
2014-01-22 12:51:53
Note that function parameters are out-Parameters - that is, you must supply variable names instead of values.
All parameters are optional, so call:Now Y M
is a valid call if you only want to get year and month.
edited Jul 15 '17 at 17:55
Peter Mortensen
13.4k1983111
13.4k1983111
answered Jan 22 '14 at 11:59
Tomalak
256k51423540
256k51423540
add a comment |
add a comment |
This is what I've used:
::Date Variables - replace characters that are not legal as part of filesystem file names (to produce name like "backup_04.15.08.7z")
SET DT=%date%
SET DT=%DT:/=.%
SET DT=%DT:-=.%
If you want further ideas for automating backups to 7-Zip archives, I have a free/open project you can use or review for ideas: http://wittman.org/ziparcy/
On my system %date% contains "Tue 10/14/2008". So, you'll still need to cut off (or otherwise deal with) the "Tue" and the space character.
– BoltBait
Oct 14 '08 at 22:34
Hi @micahwittman. Is it possible to load files with created date using xp_cmdshell in SQL Server ? I have tried "forfiles" command but to no avail. I have asked a question on stackoverflow, please kindly see the link @ stackoverflow.com/q/32293517/3327081
– kolunar
Sep 2 '15 at 13:17
add a comment |
This is what I've used:
::Date Variables - replace characters that are not legal as part of filesystem file names (to produce name like "backup_04.15.08.7z")
SET DT=%date%
SET DT=%DT:/=.%
SET DT=%DT:-=.%
If you want further ideas for automating backups to 7-Zip archives, I have a free/open project you can use or review for ideas: http://wittman.org/ziparcy/
On my system %date% contains "Tue 10/14/2008". So, you'll still need to cut off (or otherwise deal with) the "Tue" and the space character.
– BoltBait
Oct 14 '08 at 22:34
Hi @micahwittman. Is it possible to load files with created date using xp_cmdshell in SQL Server ? I have tried "forfiles" command but to no avail. I have asked a question on stackoverflow, please kindly see the link @ stackoverflow.com/q/32293517/3327081
– kolunar
Sep 2 '15 at 13:17
add a comment |
This is what I've used:
::Date Variables - replace characters that are not legal as part of filesystem file names (to produce name like "backup_04.15.08.7z")
SET DT=%date%
SET DT=%DT:/=.%
SET DT=%DT:-=.%
If you want further ideas for automating backups to 7-Zip archives, I have a free/open project you can use or review for ideas: http://wittman.org/ziparcy/
This is what I've used:
::Date Variables - replace characters that are not legal as part of filesystem file names (to produce name like "backup_04.15.08.7z")
SET DT=%date%
SET DT=%DT:/=.%
SET DT=%DT:-=.%
If you want further ideas for automating backups to 7-Zip archives, I have a free/open project you can use or review for ideas: http://wittman.org/ziparcy/
edited Jul 15 '17 at 11:40
Peter Mortensen
13.4k1983111
13.4k1983111
answered Oct 14 '08 at 22:29
micahwittman
10.1k12535
10.1k12535
On my system %date% contains "Tue 10/14/2008". So, you'll still need to cut off (or otherwise deal with) the "Tue" and the space character.
– BoltBait
Oct 14 '08 at 22:34
Hi @micahwittman. Is it possible to load files with created date using xp_cmdshell in SQL Server ? I have tried "forfiles" command but to no avail. I have asked a question on stackoverflow, please kindly see the link @ stackoverflow.com/q/32293517/3327081
– kolunar
Sep 2 '15 at 13:17
add a comment |
On my system %date% contains "Tue 10/14/2008". So, you'll still need to cut off (or otherwise deal with) the "Tue" and the space character.
– BoltBait
Oct 14 '08 at 22:34
Hi @micahwittman. Is it possible to load files with created date using xp_cmdshell in SQL Server ? I have tried "forfiles" command but to no avail. I have asked a question on stackoverflow, please kindly see the link @ stackoverflow.com/q/32293517/3327081
– kolunar
Sep 2 '15 at 13:17
On my system %date% contains "Tue 10/14/2008". So, you'll still need to cut off (or otherwise deal with) the "Tue" and the space character.
– BoltBait
Oct 14 '08 at 22:34
On my system %date% contains "Tue 10/14/2008". So, you'll still need to cut off (or otherwise deal with) the "Tue" and the space character.
– BoltBait
Oct 14 '08 at 22:34
Hi @micahwittman. Is it possible to load files with created date using xp_cmdshell in SQL Server ? I have tried "forfiles" command but to no avail. I have asked a question on stackoverflow, please kindly see the link @ stackoverflow.com/q/32293517/3327081
– kolunar
Sep 2 '15 at 13:17
Hi @micahwittman. Is it possible to load files with created date using xp_cmdshell in SQL Server ? I have tried "forfiles" command but to no avail. I have asked a question on stackoverflow, please kindly see the link @ stackoverflow.com/q/32293517/3327081
– kolunar
Sep 2 '15 at 13:17
add a comment |
I had a similar problem. I have an automatic daily download from an FTP server of an encrypted file. I wanted to decrypt the file using gpg, rename the file to the current date (YYYYMMDD format) and drop the decrypted file into a folder for the correct department.
I went through several suggestions for renaming the file according to date and was having no luck until I stumbled upon this simple solution.
for /f "tokens=1-5 delims=/ " %%d in ("%date%") do rename "decrypted.txt" %%g-%%e-%%f.txt
It worked perfectly (i.e., the filename comes out as "2011-06-14.txt").
(Source)
add a comment |
I had a similar problem. I have an automatic daily download from an FTP server of an encrypted file. I wanted to decrypt the file using gpg, rename the file to the current date (YYYYMMDD format) and drop the decrypted file into a folder for the correct department.
I went through several suggestions for renaming the file according to date and was having no luck until I stumbled upon this simple solution.
for /f "tokens=1-5 delims=/ " %%d in ("%date%") do rename "decrypted.txt" %%g-%%e-%%f.txt
It worked perfectly (i.e., the filename comes out as "2011-06-14.txt").
(Source)
add a comment |
I had a similar problem. I have an automatic daily download from an FTP server of an encrypted file. I wanted to decrypt the file using gpg, rename the file to the current date (YYYYMMDD format) and drop the decrypted file into a folder for the correct department.
I went through several suggestions for renaming the file according to date and was having no luck until I stumbled upon this simple solution.
for /f "tokens=1-5 delims=/ " %%d in ("%date%") do rename "decrypted.txt" %%g-%%e-%%f.txt
It worked perfectly (i.e., the filename comes out as "2011-06-14.txt").
(Source)
I had a similar problem. I have an automatic daily download from an FTP server of an encrypted file. I wanted to decrypt the file using gpg, rename the file to the current date (YYYYMMDD format) and drop the decrypted file into a folder for the correct department.
I went through several suggestions for renaming the file according to date and was having no luck until I stumbled upon this simple solution.
for /f "tokens=1-5 delims=/ " %%d in ("%date%") do rename "decrypted.txt" %%g-%%e-%%f.txt
It worked perfectly (i.e., the filename comes out as "2011-06-14.txt").
(Source)
edited Oct 15 '12 at 8:49
bluish
13.7k1693146
13.7k1693146
answered Jun 14 '11 at 19:02
KChiki
411
411
add a comment |
add a comment |
http://sourceforge.net/projects/unxutils/files/
Look inside the ZIP file for something called "Date.exe" and rename it "DateFormat.exe" (to avoid conflicts).
Put it in your Windows system32 folder.
It has a lot of "date output" options.
For help, use DateFormat.exe --h
I'm not sure how you would put its output into an environment variable... using SET.
1
Thanks, although this question is specifically for doing it without downloading additional tools.
– Rory
Oct 31 '10 at 12:22
add a comment |
http://sourceforge.net/projects/unxutils/files/
Look inside the ZIP file for something called "Date.exe" and rename it "DateFormat.exe" (to avoid conflicts).
Put it in your Windows system32 folder.
It has a lot of "date output" options.
For help, use DateFormat.exe --h
I'm not sure how you would put its output into an environment variable... using SET.
1
Thanks, although this question is specifically for doing it without downloading additional tools.
– Rory
Oct 31 '10 at 12:22
add a comment |
http://sourceforge.net/projects/unxutils/files/
Look inside the ZIP file for something called "Date.exe" and rename it "DateFormat.exe" (to avoid conflicts).
Put it in your Windows system32 folder.
It has a lot of "date output" options.
For help, use DateFormat.exe --h
I'm not sure how you would put its output into an environment variable... using SET.
http://sourceforge.net/projects/unxutils/files/
Look inside the ZIP file for something called "Date.exe" and rename it "DateFormat.exe" (to avoid conflicts).
Put it in your Windows system32 folder.
It has a lot of "date output" options.
For help, use DateFormat.exe --h
I'm not sure how you would put its output into an environment variable... using SET.
edited Jul 15 '17 at 17:40
Peter Mortensen
13.4k1983111
13.4k1983111
answered Oct 31 '10 at 4:45
Sally
8024
8024
1
Thanks, although this question is specifically for doing it without downloading additional tools.
– Rory
Oct 31 '10 at 12:22
add a comment |
1
Thanks, although this question is specifically for doing it without downloading additional tools.
– Rory
Oct 31 '10 at 12:22
1
1
Thanks, although this question is specifically for doing it without downloading additional tools.
– Rory
Oct 31 '10 at 12:22
Thanks, although this question is specifically for doing it without downloading additional tools.
– Rory
Oct 31 '10 at 12:22
add a comment |
Regional independent solution generating the ISO date format:
rem save the existing format definition
for /f "skip=2 tokens=3" %%a in ('reg query "HKCUControl PanelInternational" /v sShortDate') do set FORMAT=%%a
rem set ISO specific format definition
reg add "HKCUControl PanelInternational" /v sShortDate /t REG_SZ /f /d yyyy-MM-dd 1>nul:
rem query the date in the ISO specific format
set ISODATE=%DATE%
rem restore previous format definition
reg add "HKCUControl PanelInternational" /v sShortDate /t REG_SZ /f /d %FORMAT% 1>nul:
What could still be optimized:
Other processes might get confused if using the date format in the short period while it is modified. So parsing the output according to the existing format string could be 'safer' - but will be more complicated
you could reg query iDate (technet.microsoft.com/en-us/library/cc978637.aspx) and conditionally proceed (3 possible values according to technet) - although I have not tried this yet.
– Vincent De Smet
May 5 '12 at 19:08
add a comment |
Regional independent solution generating the ISO date format:
rem save the existing format definition
for /f "skip=2 tokens=3" %%a in ('reg query "HKCUControl PanelInternational" /v sShortDate') do set FORMAT=%%a
rem set ISO specific format definition
reg add "HKCUControl PanelInternational" /v sShortDate /t REG_SZ /f /d yyyy-MM-dd 1>nul:
rem query the date in the ISO specific format
set ISODATE=%DATE%
rem restore previous format definition
reg add "HKCUControl PanelInternational" /v sShortDate /t REG_SZ /f /d %FORMAT% 1>nul:
What could still be optimized:
Other processes might get confused if using the date format in the short period while it is modified. So parsing the output according to the existing format string could be 'safer' - but will be more complicated
you could reg query iDate (technet.microsoft.com/en-us/library/cc978637.aspx) and conditionally proceed (3 possible values according to technet) - although I have not tried this yet.
– Vincent De Smet
May 5 '12 at 19:08
add a comment |
Regional independent solution generating the ISO date format:
rem save the existing format definition
for /f "skip=2 tokens=3" %%a in ('reg query "HKCUControl PanelInternational" /v sShortDate') do set FORMAT=%%a
rem set ISO specific format definition
reg add "HKCUControl PanelInternational" /v sShortDate /t REG_SZ /f /d yyyy-MM-dd 1>nul:
rem query the date in the ISO specific format
set ISODATE=%DATE%
rem restore previous format definition
reg add "HKCUControl PanelInternational" /v sShortDate /t REG_SZ /f /d %FORMAT% 1>nul:
What could still be optimized:
Other processes might get confused if using the date format in the short period while it is modified. So parsing the output according to the existing format string could be 'safer' - but will be more complicated
Regional independent solution generating the ISO date format:
rem save the existing format definition
for /f "skip=2 tokens=3" %%a in ('reg query "HKCUControl PanelInternational" /v sShortDate') do set FORMAT=%%a
rem set ISO specific format definition
reg add "HKCUControl PanelInternational" /v sShortDate /t REG_SZ /f /d yyyy-MM-dd 1>nul:
rem query the date in the ISO specific format
set ISODATE=%DATE%
rem restore previous format definition
reg add "HKCUControl PanelInternational" /v sShortDate /t REG_SZ /f /d %FORMAT% 1>nul:
What could still be optimized:
Other processes might get confused if using the date format in the short period while it is modified. So parsing the output according to the existing format string could be 'safer' - but will be more complicated
answered Sep 6 '11 at 12:09
V15I0N
375314
375314
you could reg query iDate (technet.microsoft.com/en-us/library/cc978637.aspx) and conditionally proceed (3 possible values according to technet) - although I have not tried this yet.
– Vincent De Smet
May 5 '12 at 19:08
add a comment |
you could reg query iDate (technet.microsoft.com/en-us/library/cc978637.aspx) and conditionally proceed (3 possible values according to technet) - although I have not tried this yet.
– Vincent De Smet
May 5 '12 at 19:08
you could reg query iDate (technet.microsoft.com/en-us/library/cc978637.aspx) and conditionally proceed (3 possible values according to technet) - although I have not tried this yet.
– Vincent De Smet
May 5 '12 at 19:08
you could reg query iDate (technet.microsoft.com/en-us/library/cc978637.aspx) and conditionally proceed (3 possible values according to technet) - although I have not tried this yet.
– Vincent De Smet
May 5 '12 at 19:08
add a comment |
:: GetDate.cmd -> Uses WMIC.exe to get current date and time in ISO 8601 format
:: - Sets environment variables %_isotime% and %_now% to current time
:: - On failure, clears these environment variables
:: Inspired on -> https://ss64.com/nt/syntax-getdate.html
:: - (cX) 2017 adolfo.dimare@gmail.com
:: - http://stackoverflow.com/questions/203090
@echo off
set _isotime=
set _now=
:: Check that WMIC.exe is available
WMIC.exe Alias /? >NUL 2>&1 || goto _WMIC_MISSING_
if not (%1)==() goto _help
SetLocal EnableDelayedExpansion
:: Use WMIC.exe to retrieve date and time
FOR /F "skip=1 tokens=1-6" %%G IN ('WMIC.exe Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
IF "%%~L"=="" goto _WMIC_done_
set _yyyy=%%L
set _mm=00%%J
set _dd=00%%G
set _hour=00%%H
set _minute=00%%I
set _second=00%%K
)
:_WMIC_done_
:: 1 2 3 4 5 6
:: %%G %%H %%I %%J %%K %%L
:: Day Hour Minute Month Second Year
:: 27 9 35 4 38 2017
:: Remove excess leading zeroes
set _mm=%_mm:~-2%
set _dd=%_dd:~-2%
set _hour=%_hour:~-2%
set _minute=%_minute:~-2%
set _second=%_second:~-2%
:: Syntax -> %variable:~num_chars_to_skip,num_chars_to_keep%
:: Set date/time in ISO 8601 format:
Set _isotime=%_yyyy%-%_mm%-%_dd%T%_hour%:%_minute%:%_second%
:: -> http://google.com/search?num=100&q=ISO+8601+format
if 1%_hour% LSS 112 set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%am
if 1%_hour% LSS 112 goto _skip_12_
set /a _hour=1%_hour%-12
set _hour=%_hour:~-2%
set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%pm
:: -> https://ss64.com/nt/if.html
:: -> http://google.com/search?num=100&q=SetLocal+EndLocal+Windows
:: 'if () else ()' will NOT set %_now% correctly !?
:_skip_12_
EndLocal & set _isotime=%_isotime% & set _now=%_now%
goto _out
:_WMIC_MISSING_
echo.
echo WMIC.exe command not available
echo - WMIC.exe needs Administrator privileges to run in Windows
echo - Usually the path to WMIC.exe is "%windir%System32wbemWMIC.exe"
:_help
echo.
echo GetDate.cmd: Uses WMIC.exe to get current date and time in ISO 8601 format
echo.
echo %%_now%% environment variable set to current date and time
echo %%_isotime%% environment variable to current time in ISO format
echo set _today=%%_isotime:~0,10%%
echo.
:_out
:: EOF: GetDate.cmd
add a comment |
:: GetDate.cmd -> Uses WMIC.exe to get current date and time in ISO 8601 format
:: - Sets environment variables %_isotime% and %_now% to current time
:: - On failure, clears these environment variables
:: Inspired on -> https://ss64.com/nt/syntax-getdate.html
:: - (cX) 2017 adolfo.dimare@gmail.com
:: - http://stackoverflow.com/questions/203090
@echo off
set _isotime=
set _now=
:: Check that WMIC.exe is available
WMIC.exe Alias /? >NUL 2>&1 || goto _WMIC_MISSING_
if not (%1)==() goto _help
SetLocal EnableDelayedExpansion
:: Use WMIC.exe to retrieve date and time
FOR /F "skip=1 tokens=1-6" %%G IN ('WMIC.exe Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
IF "%%~L"=="" goto _WMIC_done_
set _yyyy=%%L
set _mm=00%%J
set _dd=00%%G
set _hour=00%%H
set _minute=00%%I
set _second=00%%K
)
:_WMIC_done_
:: 1 2 3 4 5 6
:: %%G %%H %%I %%J %%K %%L
:: Day Hour Minute Month Second Year
:: 27 9 35 4 38 2017
:: Remove excess leading zeroes
set _mm=%_mm:~-2%
set _dd=%_dd:~-2%
set _hour=%_hour:~-2%
set _minute=%_minute:~-2%
set _second=%_second:~-2%
:: Syntax -> %variable:~num_chars_to_skip,num_chars_to_keep%
:: Set date/time in ISO 8601 format:
Set _isotime=%_yyyy%-%_mm%-%_dd%T%_hour%:%_minute%:%_second%
:: -> http://google.com/search?num=100&q=ISO+8601+format
if 1%_hour% LSS 112 set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%am
if 1%_hour% LSS 112 goto _skip_12_
set /a _hour=1%_hour%-12
set _hour=%_hour:~-2%
set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%pm
:: -> https://ss64.com/nt/if.html
:: -> http://google.com/search?num=100&q=SetLocal+EndLocal+Windows
:: 'if () else ()' will NOT set %_now% correctly !?
:_skip_12_
EndLocal & set _isotime=%_isotime% & set _now=%_now%
goto _out
:_WMIC_MISSING_
echo.
echo WMIC.exe command not available
echo - WMIC.exe needs Administrator privileges to run in Windows
echo - Usually the path to WMIC.exe is "%windir%System32wbemWMIC.exe"
:_help
echo.
echo GetDate.cmd: Uses WMIC.exe to get current date and time in ISO 8601 format
echo.
echo %%_now%% environment variable set to current date and time
echo %%_isotime%% environment variable to current time in ISO format
echo set _today=%%_isotime:~0,10%%
echo.
:_out
:: EOF: GetDate.cmd
add a comment |
:: GetDate.cmd -> Uses WMIC.exe to get current date and time in ISO 8601 format
:: - Sets environment variables %_isotime% and %_now% to current time
:: - On failure, clears these environment variables
:: Inspired on -> https://ss64.com/nt/syntax-getdate.html
:: - (cX) 2017 adolfo.dimare@gmail.com
:: - http://stackoverflow.com/questions/203090
@echo off
set _isotime=
set _now=
:: Check that WMIC.exe is available
WMIC.exe Alias /? >NUL 2>&1 || goto _WMIC_MISSING_
if not (%1)==() goto _help
SetLocal EnableDelayedExpansion
:: Use WMIC.exe to retrieve date and time
FOR /F "skip=1 tokens=1-6" %%G IN ('WMIC.exe Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
IF "%%~L"=="" goto _WMIC_done_
set _yyyy=%%L
set _mm=00%%J
set _dd=00%%G
set _hour=00%%H
set _minute=00%%I
set _second=00%%K
)
:_WMIC_done_
:: 1 2 3 4 5 6
:: %%G %%H %%I %%J %%K %%L
:: Day Hour Minute Month Second Year
:: 27 9 35 4 38 2017
:: Remove excess leading zeroes
set _mm=%_mm:~-2%
set _dd=%_dd:~-2%
set _hour=%_hour:~-2%
set _minute=%_minute:~-2%
set _second=%_second:~-2%
:: Syntax -> %variable:~num_chars_to_skip,num_chars_to_keep%
:: Set date/time in ISO 8601 format:
Set _isotime=%_yyyy%-%_mm%-%_dd%T%_hour%:%_minute%:%_second%
:: -> http://google.com/search?num=100&q=ISO+8601+format
if 1%_hour% LSS 112 set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%am
if 1%_hour% LSS 112 goto _skip_12_
set /a _hour=1%_hour%-12
set _hour=%_hour:~-2%
set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%pm
:: -> https://ss64.com/nt/if.html
:: -> http://google.com/search?num=100&q=SetLocal+EndLocal+Windows
:: 'if () else ()' will NOT set %_now% correctly !?
:_skip_12_
EndLocal & set _isotime=%_isotime% & set _now=%_now%
goto _out
:_WMIC_MISSING_
echo.
echo WMIC.exe command not available
echo - WMIC.exe needs Administrator privileges to run in Windows
echo - Usually the path to WMIC.exe is "%windir%System32wbemWMIC.exe"
:_help
echo.
echo GetDate.cmd: Uses WMIC.exe to get current date and time in ISO 8601 format
echo.
echo %%_now%% environment variable set to current date and time
echo %%_isotime%% environment variable to current time in ISO format
echo set _today=%%_isotime:~0,10%%
echo.
:_out
:: EOF: GetDate.cmd
:: GetDate.cmd -> Uses WMIC.exe to get current date and time in ISO 8601 format
:: - Sets environment variables %_isotime% and %_now% to current time
:: - On failure, clears these environment variables
:: Inspired on -> https://ss64.com/nt/syntax-getdate.html
:: - (cX) 2017 adolfo.dimare@gmail.com
:: - http://stackoverflow.com/questions/203090
@echo off
set _isotime=
set _now=
:: Check that WMIC.exe is available
WMIC.exe Alias /? >NUL 2>&1 || goto _WMIC_MISSING_
if not (%1)==() goto _help
SetLocal EnableDelayedExpansion
:: Use WMIC.exe to retrieve date and time
FOR /F "skip=1 tokens=1-6" %%G IN ('WMIC.exe Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
IF "%%~L"=="" goto _WMIC_done_
set _yyyy=%%L
set _mm=00%%J
set _dd=00%%G
set _hour=00%%H
set _minute=00%%I
set _second=00%%K
)
:_WMIC_done_
:: 1 2 3 4 5 6
:: %%G %%H %%I %%J %%K %%L
:: Day Hour Minute Month Second Year
:: 27 9 35 4 38 2017
:: Remove excess leading zeroes
set _mm=%_mm:~-2%
set _dd=%_dd:~-2%
set _hour=%_hour:~-2%
set _minute=%_minute:~-2%
set _second=%_second:~-2%
:: Syntax -> %variable:~num_chars_to_skip,num_chars_to_keep%
:: Set date/time in ISO 8601 format:
Set _isotime=%_yyyy%-%_mm%-%_dd%T%_hour%:%_minute%:%_second%
:: -> http://google.com/search?num=100&q=ISO+8601+format
if 1%_hour% LSS 112 set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%am
if 1%_hour% LSS 112 goto _skip_12_
set /a _hour=1%_hour%-12
set _hour=%_hour:~-2%
set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%pm
:: -> https://ss64.com/nt/if.html
:: -> http://google.com/search?num=100&q=SetLocal+EndLocal+Windows
:: 'if () else ()' will NOT set %_now% correctly !?
:_skip_12_
EndLocal & set _isotime=%_isotime% & set _now=%_now%
goto _out
:_WMIC_MISSING_
echo.
echo WMIC.exe command not available
echo - WMIC.exe needs Administrator privileges to run in Windows
echo - Usually the path to WMIC.exe is "%windir%System32wbemWMIC.exe"
:_help
echo.
echo GetDate.cmd: Uses WMIC.exe to get current date and time in ISO 8601 format
echo.
echo %%_now%% environment variable set to current date and time
echo %%_isotime%% environment variable to current time in ISO format
echo set _today=%%_isotime:~0,10%%
echo.
:_out
:: EOF: GetDate.cmd
edited May 11 '17 at 15:42
answered May 10 '17 at 22:23
Adolfo
19714
19714
add a comment |
add a comment |
Given a known locality, for reference in functional form. The ECHOTIMESTAMP
call shows how to get the timestamp into a variable (DTS
in this example.)
@ECHO off
CALL :ECHOTIMESTAMP
GOTO END
:TIMESTAMP
SETLOCAL EnableDelayedExpansion
SET DATESTAMP=!DATE:~10,4!-!DATE:~4,2!-!DATE:~7,2!
SET TIMESTAMP=!TIME:~0,2!-!TIME:~3,2!-!TIME:~6,2!
SET DTS=!DATESTAMP: =0!-!TIMESTAMP: =0!
ENDLOCAL & SET "%~1=%DTS%"
GOTO :EOF
:ECHOTIMESTAMP
SETLOCAL
CALL :TIMESTAMP DTS
ECHO %DTS%
ENDLOCAL
GOTO :EOF
:END
EXIT /b 0
And saved to file, timestamp.bat, here's the output:
It seems that this comes with the regional issue - this doesn't work in all English machines.
– SteveFest
Jul 21 '17 at 1:11
Not surprised, @SteveFest . If it were possible to temporarily set the locale, that might help to provide a global solution, but it seems it's necessary to the know the region in advance. Is your locale en-US or en-SomewhereElse?
– bvj
Jul 21 '17 at 7:01
Mine is zh-HK, with edited date time format
– SteveFest
Jul 21 '17 at 7:02
@SteveFest I suppose it would be possible to build up a list of locales where each includes date/time expressions with a sample to validate. I'm super busy, but I'll try to update my answer to illustrate. Could you show me samples of the HK time/date outputs? I may be foolishly assuming zh-HK prints digits at fixed offsets.
– bvj
Jul 23 '17 at 4:10
zh-HK:(yy)yy年m月d日 hh:mm
- no leading zeros. (yy) could be ignore as we have 2 digit year, or 4 digit year. But please note one thing: the date time format can be changed per machine.
– SteveFest
Jul 23 '17 at 4:42
|
show 4 more comments
Given a known locality, for reference in functional form. The ECHOTIMESTAMP
call shows how to get the timestamp into a variable (DTS
in this example.)
@ECHO off
CALL :ECHOTIMESTAMP
GOTO END
:TIMESTAMP
SETLOCAL EnableDelayedExpansion
SET DATESTAMP=!DATE:~10,4!-!DATE:~4,2!-!DATE:~7,2!
SET TIMESTAMP=!TIME:~0,2!-!TIME:~3,2!-!TIME:~6,2!
SET DTS=!DATESTAMP: =0!-!TIMESTAMP: =0!
ENDLOCAL & SET "%~1=%DTS%"
GOTO :EOF
:ECHOTIMESTAMP
SETLOCAL
CALL :TIMESTAMP DTS
ECHO %DTS%
ENDLOCAL
GOTO :EOF
:END
EXIT /b 0
And saved to file, timestamp.bat, here's the output:
It seems that this comes with the regional issue - this doesn't work in all English machines.
– SteveFest
Jul 21 '17 at 1:11
Not surprised, @SteveFest . If it were possible to temporarily set the locale, that might help to provide a global solution, but it seems it's necessary to the know the region in advance. Is your locale en-US or en-SomewhereElse?
– bvj
Jul 21 '17 at 7:01
Mine is zh-HK, with edited date time format
– SteveFest
Jul 21 '17 at 7:02
@SteveFest I suppose it would be possible to build up a list of locales where each includes date/time expressions with a sample to validate. I'm super busy, but I'll try to update my answer to illustrate. Could you show me samples of the HK time/date outputs? I may be foolishly assuming zh-HK prints digits at fixed offsets.
– bvj
Jul 23 '17 at 4:10
zh-HK:(yy)yy年m月d日 hh:mm
- no leading zeros. (yy) could be ignore as we have 2 digit year, or 4 digit year. But please note one thing: the date time format can be changed per machine.
– SteveFest
Jul 23 '17 at 4:42
|
show 4 more comments
Given a known locality, for reference in functional form. The ECHOTIMESTAMP
call shows how to get the timestamp into a variable (DTS
in this example.)
@ECHO off
CALL :ECHOTIMESTAMP
GOTO END
:TIMESTAMP
SETLOCAL EnableDelayedExpansion
SET DATESTAMP=!DATE:~10,4!-!DATE:~4,2!-!DATE:~7,2!
SET TIMESTAMP=!TIME:~0,2!-!TIME:~3,2!-!TIME:~6,2!
SET DTS=!DATESTAMP: =0!-!TIMESTAMP: =0!
ENDLOCAL & SET "%~1=%DTS%"
GOTO :EOF
:ECHOTIMESTAMP
SETLOCAL
CALL :TIMESTAMP DTS
ECHO %DTS%
ENDLOCAL
GOTO :EOF
:END
EXIT /b 0
And saved to file, timestamp.bat, here's the output:
Given a known locality, for reference in functional form. The ECHOTIMESTAMP
call shows how to get the timestamp into a variable (DTS
in this example.)
@ECHO off
CALL :ECHOTIMESTAMP
GOTO END
:TIMESTAMP
SETLOCAL EnableDelayedExpansion
SET DATESTAMP=!DATE:~10,4!-!DATE:~4,2!-!DATE:~7,2!
SET TIMESTAMP=!TIME:~0,2!-!TIME:~3,2!-!TIME:~6,2!
SET DTS=!DATESTAMP: =0!-!TIMESTAMP: =0!
ENDLOCAL & SET "%~1=%DTS%"
GOTO :EOF
:ECHOTIMESTAMP
SETLOCAL
CALL :TIMESTAMP DTS
ECHO %DTS%
ENDLOCAL
GOTO :EOF
:END
EXIT /b 0
And saved to file, timestamp.bat, here's the output:
answered Aug 11 '16 at 20:07
bvj
2,2432221
2,2432221
It seems that this comes with the regional issue - this doesn't work in all English machines.
– SteveFest
Jul 21 '17 at 1:11
Not surprised, @SteveFest . If it were possible to temporarily set the locale, that might help to provide a global solution, but it seems it's necessary to the know the region in advance. Is your locale en-US or en-SomewhereElse?
– bvj
Jul 21 '17 at 7:01
Mine is zh-HK, with edited date time format
– SteveFest
Jul 21 '17 at 7:02
@SteveFest I suppose it would be possible to build up a list of locales where each includes date/time expressions with a sample to validate. I'm super busy, but I'll try to update my answer to illustrate. Could you show me samples of the HK time/date outputs? I may be foolishly assuming zh-HK prints digits at fixed offsets.
– bvj
Jul 23 '17 at 4:10
zh-HK:(yy)yy年m月d日 hh:mm
- no leading zeros. (yy) could be ignore as we have 2 digit year, or 4 digit year. But please note one thing: the date time format can be changed per machine.
– SteveFest
Jul 23 '17 at 4:42
|
show 4 more comments
It seems that this comes with the regional issue - this doesn't work in all English machines.
– SteveFest
Jul 21 '17 at 1:11
Not surprised, @SteveFest . If it were possible to temporarily set the locale, that might help to provide a global solution, but it seems it's necessary to the know the region in advance. Is your locale en-US or en-SomewhereElse?
– bvj
Jul 21 '17 at 7:01
Mine is zh-HK, with edited date time format
– SteveFest
Jul 21 '17 at 7:02
@SteveFest I suppose it would be possible to build up a list of locales where each includes date/time expressions with a sample to validate. I'm super busy, but I'll try to update my answer to illustrate. Could you show me samples of the HK time/date outputs? I may be foolishly assuming zh-HK prints digits at fixed offsets.
– bvj
Jul 23 '17 at 4:10
zh-HK:(yy)yy年m月d日 hh:mm
- no leading zeros. (yy) could be ignore as we have 2 digit year, or 4 digit year. But please note one thing: the date time format can be changed per machine.
– SteveFest
Jul 23 '17 at 4:42
It seems that this comes with the regional issue - this doesn't work in all English machines.
– SteveFest
Jul 21 '17 at 1:11
It seems that this comes with the regional issue - this doesn't work in all English machines.
– SteveFest
Jul 21 '17 at 1:11
Not surprised, @SteveFest . If it were possible to temporarily set the locale, that might help to provide a global solution, but it seems it's necessary to the know the region in advance. Is your locale en-US or en-SomewhereElse?
– bvj
Jul 21 '17 at 7:01
Not surprised, @SteveFest . If it were possible to temporarily set the locale, that might help to provide a global solution, but it seems it's necessary to the know the region in advance. Is your locale en-US or en-SomewhereElse?
– bvj
Jul 21 '17 at 7:01
Mine is zh-HK, with edited date time format
– SteveFest
Jul 21 '17 at 7:02
Mine is zh-HK, with edited date time format
– SteveFest
Jul 21 '17 at 7:02
@SteveFest I suppose it would be possible to build up a list of locales where each includes date/time expressions with a sample to validate. I'm super busy, but I'll try to update my answer to illustrate. Could you show me samples of the HK time/date outputs? I may be foolishly assuming zh-HK prints digits at fixed offsets.
– bvj
Jul 23 '17 at 4:10
@SteveFest I suppose it would be possible to build up a list of locales where each includes date/time expressions with a sample to validate. I'm super busy, but I'll try to update my answer to illustrate. Could you show me samples of the HK time/date outputs? I may be foolishly assuming zh-HK prints digits at fixed offsets.
– bvj
Jul 23 '17 at 4:10
zh-HK:
(yy)yy年m月d日 hh:mm
- no leading zeros. (yy) could be ignore as we have 2 digit year, or 4 digit year. But please note one thing: the date time format can be changed per machine.– SteveFest
Jul 23 '17 at 4:42
zh-HK:
(yy)yy年m月d日 hh:mm
- no leading zeros. (yy) could be ignore as we have 2 digit year, or 4 digit year. But please note one thing: the date time format can be changed per machine.– SteveFest
Jul 23 '17 at 4:42
|
show 4 more comments
With Windows 7, this code works for me:
SET DATE=%date%
SET YEAR=%DATE:~0,4%
SET MONTH=%DATE:~5,2%
SET DAY=%DATE:~8,2%
ECHO %YEAR%
ECHO %MONTH%
ECHO %DAY%
SET DATE_FRM=%YEAR%-%MONTH%-%DAY%
ECHO %DATE_FRM%
And again. It's nice that it works on your machine, but you missed the pointindependent of the regional settings of the machine
– jeb
Aug 16 '16 at 11:06
Ok, but others example don't work at all for me
– Frizz1977
Aug 16 '16 at 11:30
add a comment |
With Windows 7, this code works for me:
SET DATE=%date%
SET YEAR=%DATE:~0,4%
SET MONTH=%DATE:~5,2%
SET DAY=%DATE:~8,2%
ECHO %YEAR%
ECHO %MONTH%
ECHO %DAY%
SET DATE_FRM=%YEAR%-%MONTH%-%DAY%
ECHO %DATE_FRM%
And again. It's nice that it works on your machine, but you missed the pointindependent of the regional settings of the machine
– jeb
Aug 16 '16 at 11:06
Ok, but others example don't work at all for me
– Frizz1977
Aug 16 '16 at 11:30
add a comment |
With Windows 7, this code works for me:
SET DATE=%date%
SET YEAR=%DATE:~0,4%
SET MONTH=%DATE:~5,2%
SET DAY=%DATE:~8,2%
ECHO %YEAR%
ECHO %MONTH%
ECHO %DAY%
SET DATE_FRM=%YEAR%-%MONTH%-%DAY%
ECHO %DATE_FRM%
With Windows 7, this code works for me:
SET DATE=%date%
SET YEAR=%DATE:~0,4%
SET MONTH=%DATE:~5,2%
SET DAY=%DATE:~8,2%
ECHO %YEAR%
ECHO %MONTH%
ECHO %DAY%
SET DATE_FRM=%YEAR%-%MONTH%-%DAY%
ECHO %DATE_FRM%
edited Mar 30 '17 at 20:40
Burgi
373418
373418
answered Aug 16 '16 at 10:44
Frizz1977
659917
659917
And again. It's nice that it works on your machine, but you missed the pointindependent of the regional settings of the machine
– jeb
Aug 16 '16 at 11:06
Ok, but others example don't work at all for me
– Frizz1977
Aug 16 '16 at 11:30
add a comment |
And again. It's nice that it works on your machine, but you missed the pointindependent of the regional settings of the machine
– jeb
Aug 16 '16 at 11:06
Ok, but others example don't work at all for me
– Frizz1977
Aug 16 '16 at 11:30
And again. It's nice that it works on your machine, but you missed the point
independent of the regional settings of the machine
– jeb
Aug 16 '16 at 11:06
And again. It's nice that it works on your machine, but you missed the point
independent of the regional settings of the machine
– jeb
Aug 16 '16 at 11:06
Ok, but others example don't work at all for me
– Frizz1977
Aug 16 '16 at 11:30
Ok, but others example don't work at all for me
– Frizz1977
Aug 16 '16 at 11:30
add a comment |
I know that there are numerous ways mentioned already. But here is my way to break it down to understand how it is done. Hopefully, it is helpful for someone who like step by step method.
:: Check your local date format
echo %date%
:: Output is Mon 08/15/2016
:: get day (start index, number of characters)
:: (index starts with zero)
set myday=%DATE:~0,4%
echo %myday%
:: output is Mon
:: get month
set mymonth=%DATE:~4,2%
echo %mymonth%
:: output is 08
:: get date
set mydate=%DATE:~7,2%
echo %mydate%
:: output is 15
:: get year
set myyear=%DATE:~10,4%
echo %myyear%
:: output is 2016
3
You missed the pointindependent of the regional settings of the machine
– jeb
Aug 15 '16 at 16:13
add a comment |
I know that there are numerous ways mentioned already. But here is my way to break it down to understand how it is done. Hopefully, it is helpful for someone who like step by step method.
:: Check your local date format
echo %date%
:: Output is Mon 08/15/2016
:: get day (start index, number of characters)
:: (index starts with zero)
set myday=%DATE:~0,4%
echo %myday%
:: output is Mon
:: get month
set mymonth=%DATE:~4,2%
echo %mymonth%
:: output is 08
:: get date
set mydate=%DATE:~7,2%
echo %mydate%
:: output is 15
:: get year
set myyear=%DATE:~10,4%
echo %myyear%
:: output is 2016
3
You missed the pointindependent of the regional settings of the machine
– jeb
Aug 15 '16 at 16:13
add a comment |
I know that there are numerous ways mentioned already. But here is my way to break it down to understand how it is done. Hopefully, it is helpful for someone who like step by step method.
:: Check your local date format
echo %date%
:: Output is Mon 08/15/2016
:: get day (start index, number of characters)
:: (index starts with zero)
set myday=%DATE:~0,4%
echo %myday%
:: output is Mon
:: get month
set mymonth=%DATE:~4,2%
echo %mymonth%
:: output is 08
:: get date
set mydate=%DATE:~7,2%
echo %mydate%
:: output is 15
:: get year
set myyear=%DATE:~10,4%
echo %myyear%
:: output is 2016
I know that there are numerous ways mentioned already. But here is my way to break it down to understand how it is done. Hopefully, it is helpful for someone who like step by step method.
:: Check your local date format
echo %date%
:: Output is Mon 08/15/2016
:: get day (start index, number of characters)
:: (index starts with zero)
set myday=%DATE:~0,4%
echo %myday%
:: output is Mon
:: get month
set mymonth=%DATE:~4,2%
echo %mymonth%
:: output is 08
:: get date
set mydate=%DATE:~7,2%
echo %mydate%
:: output is 15
:: get year
set myyear=%DATE:~10,4%
echo %myyear%
:: output is 2016
answered Aug 15 '16 at 15:57
Cricrazy
394114
394114
3
You missed the pointindependent of the regional settings of the machine
– jeb
Aug 15 '16 at 16:13
add a comment |
3
You missed the pointindependent of the regional settings of the machine
– jeb
Aug 15 '16 at 16:13
3
3
You missed the point
independent of the regional settings of the machine
– jeb
Aug 15 '16 at 16:13
You missed the point
independent of the regional settings of the machine
– jeb
Aug 15 '16 at 16:13
add a comment |
I note that the o/p did not ask for a region-independent solution. My solution is for the UK though.
This is the simplest possible solution, a 1-line solution, for use in a Batch file:
FOR /F "tokens=1-3 delims=/" %%A IN ("%date%") DO (SET today=%%C-%%B-%%A)
echo %today%
2
He mentioned a region independent solution...particularly because of the regional settings issue with using date
. Btw. Your solution is the same as the twenty other answers.
– jeb
Dec 6 at 10:57
Yeah, but mine actually could (optionally) be used on the command line. What is the merit in posting 35 lines of code, if one line of code will provide the same solution?
– Ed999
Dec 6 at 18:37
I can't see any relevant difference to the old answers of @Matthew Johnson, 2010 or @KChiki, 2011
– jeb
Dec 7 at 7:27
add a comment |
I note that the o/p did not ask for a region-independent solution. My solution is for the UK though.
This is the simplest possible solution, a 1-line solution, for use in a Batch file:
FOR /F "tokens=1-3 delims=/" %%A IN ("%date%") DO (SET today=%%C-%%B-%%A)
echo %today%
2
He mentioned a region independent solution...particularly because of the regional settings issue with using date
. Btw. Your solution is the same as the twenty other answers.
– jeb
Dec 6 at 10:57
Yeah, but mine actually could (optionally) be used on the command line. What is the merit in posting 35 lines of code, if one line of code will provide the same solution?
– Ed999
Dec 6 at 18:37
I can't see any relevant difference to the old answers of @Matthew Johnson, 2010 or @KChiki, 2011
– jeb
Dec 7 at 7:27
add a comment |
I note that the o/p did not ask for a region-independent solution. My solution is for the UK though.
This is the simplest possible solution, a 1-line solution, for use in a Batch file:
FOR /F "tokens=1-3 delims=/" %%A IN ("%date%") DO (SET today=%%C-%%B-%%A)
echo %today%
I note that the o/p did not ask for a region-independent solution. My solution is for the UK though.
This is the simplest possible solution, a 1-line solution, for use in a Batch file:
FOR /F "tokens=1-3 delims=/" %%A IN ("%date%") DO (SET today=%%C-%%B-%%A)
echo %today%
answered Dec 6 at 10:13
Ed999
524510
524510
2
He mentioned a region independent solution...particularly because of the regional settings issue with using date
. Btw. Your solution is the same as the twenty other answers.
– jeb
Dec 6 at 10:57
Yeah, but mine actually could (optionally) be used on the command line. What is the merit in posting 35 lines of code, if one line of code will provide the same solution?
– Ed999
Dec 6 at 18:37
I can't see any relevant difference to the old answers of @Matthew Johnson, 2010 or @KChiki, 2011
– jeb
Dec 7 at 7:27
add a comment |
2
He mentioned a region independent solution...particularly because of the regional settings issue with using date
. Btw. Your solution is the same as the twenty other answers.
– jeb
Dec 6 at 10:57
Yeah, but mine actually could (optionally) be used on the command line. What is the merit in posting 35 lines of code, if one line of code will provide the same solution?
– Ed999
Dec 6 at 18:37
I can't see any relevant difference to the old answers of @Matthew Johnson, 2010 or @KChiki, 2011
– jeb
Dec 7 at 7:27
2
2
He mentioned a region independent solution
...particularly because of the regional settings issue with using date
. Btw. Your solution is the same as the twenty other answers.– jeb
Dec 6 at 10:57
He mentioned a region independent solution
...particularly because of the regional settings issue with using date
. Btw. Your solution is the same as the twenty other answers.– jeb
Dec 6 at 10:57
Yeah, but mine actually could (optionally) be used on the command line. What is the merit in posting 35 lines of code, if one line of code will provide the same solution?
– Ed999
Dec 6 at 18:37
Yeah, but mine actually could (optionally) be used on the command line. What is the merit in posting 35 lines of code, if one line of code will provide the same solution?
– Ed999
Dec 6 at 18:37
I can't see any relevant difference to the old answers of @Matthew Johnson, 2010 or @KChiki, 2011
– jeb
Dec 7 at 7:27
I can't see any relevant difference to the old answers of @Matthew Johnson, 2010 or @KChiki, 2011
– jeb
Dec 7 at 7:27
add a comment |
protected by Community♦ Apr 9 '12 at 8:44
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
4
Creating an automated backup for your code? Good for you! We should do this too :)
– Andrei Rînea
Apr 14 '10 at 16:09
18
use powershell people...
[datetime]::now.tostring("yyyy-MM-dd")
– Nacht
Oct 29 '14 at 0:03
Is it possible to load files with created date using xp_cmdshell in SQL Server ? I have asked a question on stackoverflow, please kindly see the link @ stackoverflow.com/q/32293517/3327081
– kolunar
Sep 2 '15 at 13:14