I am using this to get the date modified of a file:
#echo off
FOR %%? IN ("C:\some.exe") DO (
ECHO Last-Modified Date : %%~t?
)
The above returns something like: Last-Modified Date : 26/03/2013 14:43.
How can I take the date part from the above and compare it against another file which's name contains a date ie: 23-Sep-13.exe?
I need to be able to perform some code in the batch file if the file that contains the date in its name is later than the file modified version ie install the update.
#ECHO OFF
SETLOCAL
:: No doubt for international use, this could be retrieved from the registry
SET monthnames=Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
:: get last modified date of target file - your format as specified
:: (I used THIS BATCH FILE)
FOR %%i IN ("%~f0") DO SET target=%%~ti
:: parse the target date
FOR /f "tokens=1-3delims=/ " %%i IN ("%target%") DO SET targetf=%%k%%j%%i
::
:: parse name from 'other file'
SET other=23-Sep-13.exe
FOR /f "tokens=1-3delims=.- " %%i IN ("%other%") DO SET od=%%i&SET omn=%%j&SET oy=%%k
:: Convert monthname to number
:: #ECHO on
SET om=101
FOR %%i IN (%monthnames%) DO (
IF DEFINED omn IF /i %omn%==%%i (SET omn=) ELSE (SET /a om+=1)
)
:: Build date of 'other file' in same format (YYYYMMDD)
SET otherf=20%oy%%om:~-2%%od%
ECHO is %other% later than %target% ?
ECHO IF %otherf% gtr %targetf% GOTO later
ECHO.
::
:: parse name from 'another other file'
SET other=23-Jan-13.exe
FOR /f "tokens=1-3delims=.- " %%i IN ("%other%") DO SET od=%%i&SET omn=%%j&SET oy=%%k
:: Convert monthname to number
SET om=101
FOR %%i IN (%monthnames%) DO (
IF DEFINED omn IF /i %omn%==%%i (SET omn=) ELSE (SET /a om+=1)
)
:: Build date of 'other file' in same format (YYYYMMDD)
SET otherf=20%oy%%om:~-2%%od%
ECHO is %other% later than %target% ?
ECHO IF %otherf% gtr %targetf% GOTO later
ECHO.
Code takes date of (this batch) as the target (your 'C:\some.exe'- change to suit.
test then applied to two different filename-is-date+ext format filenames to test.
Can be easily adjusted if comparisons to 20th-Century date is required... :)
Related
I have this already initialized batch script codes running in bat file:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "_ROOT=%~dp0." & rem // (common root directory; `%~dp0.` is script's parent, `.` is current)
set "_DIR1=%_ROOT%\Directory1" & rem // (1st directory containing files)
set "_DIR2=%_ROOT%\Directory2" & rem // (2nd directory containing files)
set _MASKS="*INV*." "*SLS*." & rem // (list of quoted file masks)
set "_TMP1=%TEMP%\%~n0_1_%RANDOM%.tmp" & rem // (1st temporary file)
set "_TMP2=%TEMP%\%~n0_2_%RANDOM%.tmp" & rem // (2nd temporary file)
rem // Resolve 1st directory to be an absolute path:
for %%E in ("%_DIR1%") do set "RDIR1=%%~fE"
rem // Resolve 2nd directory to be an absolute path:
for %%E in ("%_DIR2%") do set "RDIR2=%%~fE"
rem // Write all matching files in 1st directory to 1st temporary file:
pushd "%RDIR1%" && (
for %%F in (%_MASKS%) do (
echo(%%~nxF
)
popd
) > "%_TMP1%"
rem // Write all matching files in 2nd directory to 2nd temporary file:
pushd "%RDIR2%" && (
for %%F in (%_MASKS%) do (
echo(%%~nxF
)
popd
) > "%_TMP2%"
rem // Loop over all common files from both temporary files:
for /F %%L in ('findstr /L /I /X /G:"%_TMP1%" "%_TMP2%"') do (
rem // Build absolute `wmic`-compatible file paths:
set "FILE1=%RDIR1:\=\\%\\%%L" & set "FILE2=%RDIR2:\=\\%\\%%L"
setlocal EnableDelayedExpansion
rem set "FILE1=%!FILE1:&=&!" & set "FILE2=%!FILE2:&=&!"
rem // Get standardised file date/time (last modification) of 1st file by `wmic`:
for /F %%K in ('wmic DataFile where "Name='!FILE1!'" get LastModified') do set "DATE1=%%K"
rem // Get standardised file date/time (last modification) of 2nd file by `wmic`:
for /F %%K in ('wmic DataFile where "Name='!FILE2!'" get LastModified') do set "DATE2=%%K"
rem // Compare file dates/times (last mod.) of both files and return differing ones:
if !DATE1! lss !DATE2! echo "!FILE1:\\=\!" is older than "!FILE2:\\=\!"
if !DATE1! gtr !DATE2! echo "!FILE1:\\=\!" is newer than "!FILE2:\\=\!"
if !DATE1! equ !DATE2! echo "!FILE1:\\=\!" and "!FILE2:\\=\!" are of same age
endlocal
)
rem // Clean up temporary files:
del "%_TMP1%" "%_TMP2%"
endlocal
exit /B
And I am getting this native logic issue, assuming that DATE1 has date of March 3/19/2019 09:23 AM and DATE2 has date of March 3/19/2019 10:03 AM suppose that the expected output be that Date1 has older date with Date2 but in the output it says Date1 is the same date with Date2.
here's the echo on process with what are the values in the dates:
CMD Shell:
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\Users\ksaycon>cd Desktop
C:\Users\ksaycon\Desktop>sample.bat
"C:\Users\ksaycon\Desktop\Directory1\FFPDFINV06" and "C:\Users\ksaycon
\Desktop\Directory2\FFPDFINV06" are of same age
C:\Users\ksaycon\Desktop>(
rem // Build absolute `wmic`-compatible file paths:
set "FILE1=C:\\Users\\ksaycon\\Desktop\\Directory1\\FFPDFSLS02" & set "FILE2=
C:\\Users\\ksaycon\\Desktop\\Directory2\\FFPDFSLS02"
setlocal EnableDelayedExpansion
rem set "FILE1=&=&!" & set "FILE2=&=&!"
rem // Get standardised file date/time (last modification) of 1st file by `wmic
`:
for /F %K in ('wmic DataFile where "Name='!FILE1!'" get LastModified') do set "
DATE1=%K"
rem // Get standardised file date/time (last modification) of 2nd file by `wmic
`:
for /F %K in ('wmic DataFile where "Name='!FILE2!'" get LastModified') do set "
DATE2=%K"
rem // Compare file dates/times (last mod.) of both files and return differing
ones:
if !DATE1! GTR !DATE2! echo "!FILE1:\\=\!" is newer than "!FILE2:\\=\!"
if !DATE1! LSS !DATE2! echo "!FILE1:\\=\!" is older than "!FILE2:\\=\!"
if !DATE1! equ !DATE2! echo "!FILE1:\\=\!" and "!FILE2:\\=\!" are of same age
endlocal
)
C:\Users\ksaycon\Desktop>set "DATE1=LastModified"
C:\Users\ksaycon\Desktop>set "DATE1=20190318040549.218407+480"
" \Users\ksaycon\Desktop>set "DATE1=
C:\Users\ksaycon\Desktop>set "DATE2=LastModified"
C:\Users\ksaycon\Desktop>set "DATE2=20190318095134.760320+480"
" \Users\ksaycon\Desktop>set "DATE2=
"C:\Users\ksaycon\Desktop\Directory1\FFPDFSLS02" and "C:\Users\ksaycon
\Desktop\Directory2\FFPDFSLS02" are of same age
C:\Users\ksaycon\Desktop>rem // Clean up temporary files:
C:\Users\ksaycon\Desktop>del "C:\Users\ksaycon\AppData\Local\Temp\sample_1_13650
.tmp" "C:\Users\ksaycon\AppData\Local\Temp\sample_2_27021.tmp"
C:\Users\ksaycon\Desktop>endlocal
C:\Users\ksaycon\Desktop>exit /B
C:\Users\ksaycon\Desktop>^A
I current run the below script to get the current day minus 1 and the current month. It works great for all days and month except for the 8th of every month and August of every year. I have to change the script to setting it manually for August. Does anyone know why and is there a fix.
SET m=%date:~4,2%
SET /A m -= 1
SET m=0%m%
REM ****** SET m=08 this was used because the date was not right ******
REM SET m=08
SET currMon=%date:~4,2%/%date:~10,4%
REM ****** SET PriorMon=12/2017 this was used for Year End because the date was not right ******
REM SET PriorMon=08/2018
SET PriorMon=%m:~-2%/%date:~10,4%
This is a hybrid vb/batch script. It is a proper way to get the date -1 or whatever amount of days you want:
#echo off
set day=-1
echo >"%temp%\%~n0.vbs" s=DateAdd("d",%day%,now) : d=weekday(s)
echo>>"%temp%\%~n0.vbs" WScript.Echo year(s)^& right(100+month(s),2)^& right(100+day(s),2)
for /f %%a in ('cscript /nologo "%temp%\%~n0.vbs"') do set "result=%%a"
del "%temp%\*%~n0.vbs"
set "yyyy=%result:~0,4%"
set "mm=%result:~4,2%"
set "dd=%result:~6,2%"
set "final=%dd%-%mm%-%yyyy%"
echo %final%
I simply echo the final result here which as far as today's date goes (for me as it is the 7th) should echo 06-09-2018
You can change the format of %final% as you please to suit your date..
Proper date calculatons in pure batch are possible but tedious.
Your approach relies on possibly unknown locale/user settings dependant date format.
From Win7 on Powershell is available as a tool:
On cmd line:
For /f "usebackq" %A in (`powershell -Nop -C "(Get-Date).AddDays(-1).ToString('MM\/yyyy')"`) Do Set Yesterday=%A
In a batch file:
For /f "usebackq" %%A in (`
powershell -Nop -C "(Get-Date).AddDays(-1).ToString('MM\/yyyy')"
`) Do Set Yesterday=%%A
Echo Yesterday=%Yesterday%
Modify the format string to your liking:
dd = day 2 places
MM = month 2 places
yyyy = year 4 places
Other characters have to be escaped with a backslash.
How do I add the time to this batch file when I rename the file?
The results look like this but need time also: Daily Report_Wed 08222018.pdf
#echo off
Pushd c:\Temp
pdftk *.pdf cat output %fn%.pdf
ren %fn%.pdf %fn%.xxx
del *.pdf
ren %fn%.xxx "Daily Report".pdf
for /f "tokens=1-3 delims=/" %%a in ('echo %date%') do set today=%%a%%b%%c
for %%f in (*.pdf) do ren "%%f" "%%~nf_%today%%%~xf"
mkdir "Daily Reports for Review"
move *.pdf "Daily Reports for Review"
Here's something that could get you close to what you want (I modified your 1st for loop):
e:\Work\Dev\StackOverflow>echo Date: [%date%], Time: [%time%]
Date: [2018-08-22], Time: [22:51:36.23]
e:\Work\Dev\StackOverflow>for /f "tokens=1-6 delims=/-:., " %a in ('echo %date: =0%-%time: =0%') do (echo set now=%a%b%c%d%e%f)
e:\Work\Dev\StackOverflow>(echo set now=20180822225136 )
set now=20180822225136
Notes:
Since I am directly in cmd window, and you're in a batch file you have to double the percent sign (%) for parameters (%a -> %%a, %b -> %%b, ... like you already have in your snippet). For more details, check [SS64]: Double %% symbols why are they needed in a batch file?
As you probably noticed (most likely due to "Regional settings"), my date format differs than yours (that's why I added the hyphen (-) in the delims list; also the items ordering is reversed), so you might get slightly different behaviors on different computers (things will get even worse on non English locales, as #Stephan noticed), so it's not a reliable solution (I guess this is batch processing generic)
Here's an untested example for you which uses WMIC to retrieve non locale dependent date and time values:
#Echo Off
If Exist "C:\Temp\*.pdf" (CD /D "C:\Temp") Else Exit /B
Rem The values below can be modified according to your language or preferred day names
Set "WeekDays=Sunday Monday Tuesday Wednesday Thursday Friday Saturday"
For /F %%A In ('WMIC Path Win32_LocalTime Get /Value^|FindStr "[0-9]$"') Do Set "%%A"
For /F "Tokens=1%DayOfWeek%" %%A In (". . . . . . . . . %WeekDays%") Do Set "DayName=%%A"
For %%A In (Day Hour Minute Month Second) Do Call Set "%%A=0%%%%A%%" & Call Set "%%A=%%%%A:~-2%%"
Rem Choose the output %FileName% you want from the following variables:
Rem %Year% e.g. 2018
Rem %Quarter% e.g. 3
Rem %Month% e.g. 08
Rem %WeekInMonth% e.g. 4
Rem %Day% e.g. 22
Rem %DayOfWeek% as an integer where Monday from %WeekDays% is 1 e.g. 3
Rem %DayName% as a string taken from %WeekDays% e.g. Wednesday
Rem %Hour% in 24 hr format e.g. 21
Rem %Minute% e.g. 57
Rem %Second% e.g. 53
Set "FileName=%DayName% %Month%%Day%%Year%%Hour%%Minute%%Second%"
Rem Choose the full or relative output directory name
Set "DirName=Daily Reports for Review"
If Not Exist "%DirName%\" MD "%DirName%"
PDFTK *.pdf cat output "%DirName%\%FileName%.pdf" && Del /Q *.pdf
You will need to include the full or relative path to PDFTK on the last line if it is not located in the current working directory, (C:\Temp), or in %PATH%. Other than that, you should only make modifications to values on lines beginning with Set.
Empty lines and those Remarked can be optionally removed once you've made your modifications.
What's a batch script command to touch on a file to update its date and time to the current date and time? (Modified Date)
For example, Joe Blow sends me a text document which he created months ago, when he emails me the document, I want to keep track of how old it is from the day I received it (not when he created it) so I want to update the file's date/time to the current date/time.
I have a batch script to automatically weed out files that haven't been edited within 90 days, so this is troublesome when I receive a particularly older file then all of a sudden it disappears.
And I need it via a batch script as I have hundreds of files to manage, and it's for archiving files.
I can't take all the credit, but I did look through my todo.txt to find it
Microsoft "touch" it's a KB article from like 5 years ago
The jist of it is you use copy /b MYFILENAME +,, where MYFILENAME is your file
This is an expansion on aflat's anwer.
1) Microsoft support provides an explanation and simple touch.bat script.
2) My custom touch.cmd, which expands on the MS script by including "touch /?" help text.
3) My custom midastouch.cmd, which provides several options including recursive operation and date operations.
As aflat wrote, the simple answer is:
copy /b FILENAME +,,
As you might expect, FILENAME can include relative or absolute path and wildcards like *.txt.
1. Microsoft1 support:
The following MS-DOS command updates the date and time stamps of a
file named "EXAMPLE" without altering the contents of the file. This
is similar to the TOUCH utility found in XENIX and in some third-party
MS-DOS toolkits.
COPY /B EXAMPLE +,,
The COPY command can concatenate a file onto an existing file when
used in the form:
COPY FILE1+FILE2
In this example, the contents of FILE2 are appended to FILE1, leaving FILE2 unchanged. When copying in this mode, the COPY command
switches to ASCII mode where the ^Z (0x01A) end-of-file marker is
honored.
Therefore, with the above command, the /b forces the COPY command into
binary mode, the filename is the file to be updated, the + (plus sign)
indicates that a file is to be appended, and the ,, (commas) are
placeholders for the remaining parameters (which are not included in
this example). Because the file to be appended is not specified, the
COPY command will append nothing and only update the time and date
stamps for the file.
The following batch file, TOUCH.BAT, can be used to automate the
process:
#echo off
if %1.==. goto end
if not exist %1 goto end
copy /b %1 +,, > nul
echo %1 touched!
:end
This batch file requires one parameter, the file to be "touched." If the
parameter is not supplied, line 2 will cause the batch file to
exit without doing anything. If the specified file does not exist,
line 3 will cause the batch file to exit also.
2. Touch.cmd
#echo off
:: -----------------------------------------
:: Process input parameter
:: -----------------------------------------
: Help requestes?
if "%1%"=="/?" goto help
if "%1%"=="?" goto help
if "%1%"=="" goto help
:: -----------------------------------------
:: Update Modified Date property to now
:: -----------------------------------------
if not exist %1% goto end
copy /b %1% +,, > nul
echo %1 touched!
goto end
:help
#echo off
echo :: --------------------------------------------------------------
echo :: Touch.cmd Help
echo :: --------------------------------------------------------------
echo.
echo Touch.cmd is batch script to update the Modified Date property
echo of teh specified file to the current
echo date and time.
echo.
echo Syntax: touch filename
echo where,
echo filename is the name of the name of the file to "touch."
echo filename may include a relative o full path.
echo filename may include wild cards like *.txt.
echo.
:end
3. MidasTouch.cmd
#echo off
:: -----------------------------------------
:: Find files older than specified date
:: -----------------------------------------
:: -----------------------------------------
:: Default Values
:: -----------------------------------------
set "default_path=%cd%"
set "default_err_log=%cd%\midastouch_err.log"
set /a default_date=-365
set "open_log=False"
set "recurse=True"
:: -----------------------------------------
:: Process input parameters
:: -----------------------------------------
: Help requestes?
if "%1%"=="/?" goto help
if "%1%"=="?" goto help
if /I "%1%"=="help" goto help
set "dir_in="
set "err_log="
set "dd="
:: Read in commandline arguements.
echo Arguements:
:arguement_loop
if "%1%"=="/p" (
echo Path: %2%
set dir_in=%2%
shift
goto loop_bottom)
if "%1%"=="/l" (
echo Error log: %2%
set err_log=%2%
shift
goto loop_bottom)
if "%1%"=="/-l" (
echo No error log. Output to console.
set err_log=CON
shift
goto loop_bottom)
if "%1%"=="/d" (
echo Date: %2%
set /a dd=%2%
shift
goto loop_bottom)
if "%1%"=="/o" (
echo Open log: True
set "open_log=True"
goto loop_bottom)
if "%1%"=="/-o" (
echo Open log: False
set "open_log=False"
goto loop_bottom)
if "%1%"=="/s" (
echo Recursive: True
set "recurse=True"
goto loop_bottom)
if "%1%"=="/-s" (
echo Recursive: False
set "recurse=False"
goto loop_bottom)
if not "%1%"=="" (
if "%dir_in%"=="" (
echo Path: %1%
set dir_in=%1%
goto loop_bottom)
if "%err_log%"=="" (
echo Error log: %1%
set err_log=%1%
goto loop_bottom)
if "%dd%"=="" (
echo Date: %1%
set /a dd=%1%
goto loop_bottom)
)
:loop_bottom
shift
if not "%1%"=="" goto arguement_loop
if "%dir_in%"=="" (
set dir_in=%default_path%)
if "%err_log%"=="" (
set err_log=%default_err_log%)
if "%dd%"=="" (
set /a dd=%default_date%)
:: -----------------------------------------
:: Execution
:: -----------------------------------------
:: Write header
set "header=Touch_dir.cmd Error Log"
if exist %err_log% (
del /q %err_log%)
#echo %header% >%err_log%
set cmd_str="cmd /c copy /b #path +,,"
:: Update Modified Date property to now
if /I "%recurse%"=="True" (
set cmd_str=forfiles /s /p %dir_in% /d %dd% /c %cmd_str%
) else (
set cmd_str=forfiles /p %dir_in% /d %dd% /c %cmd_str%
)
echo Command: %cmd_str% >>%err_log%
echo Errors: >>%err_log%
echo. >>%err_log%
echo Executing command: %cmd_str%
#echo Updating Modified Date of files older than date: %dd%.
#echo This may take a while. Please be patient...
#echo.
echo.
set cmd_str=%cmd_str% || #echo Failed to update: #path >>%err_log%"
%cmd_str%
:: Results
#echo Error log: %err_log%
if "%open_log%"=="True" (start %err_log%)
goto end
:help
#echo off
echo :: --------------------------------------------------------------
echo :: Touch_dir.cmd Help
echo :: --------------------------------------------------------------
echo.
echo Touch.cmd is batch script to recursively "touch" all files in a
echo folder to update their Modified Date property to the current
echo date and time.
echo.
echo Syntax: touch_dir /d directory /l err_log /m months
echo where,
echo /p path Path containing files with Modified
echo Date values to update to now.
echo (default = current directory).
echo /s (or /-s) Recursive (or not recursive) search
echo (default recursive is %recurse%).
echo /l err_log Error log: list of files not updated
echo (default err_log: midastouch_err.log).
echo /o (or /-o) Open (or do not open) error log after
echo execution (default open_log: %open_log%).
echo /d date Selects files with a last modified date greater
echo than or equal to (+), or less than or equal to
echo (-), the specified date using the
echo "MM/dd/yyyy" format; or selects files with a
echo last modified date greater than or equal to (+)
echo the current date plus "dd" days, or less than or
echo equal to (-) the current date minus "dd" days. A
echo valid "dd" number of days can be any number in
echo the range of 0 - 32768.
echo "+" is taken as default sign if not specified.
echo (default date is: %default_date%).
echo.
:end
Just to add that the same source provide a batch script.
#echo off
goto start
:usage
echo usage: TOUCH.BAT "MYFILENAME"
exit /b 0
:start
if %1.==. goto usage
if not exist %1 goto usage
copy /b %1 +,, > nul
echo %1 touched!
exit /b 0
hello i got a batch file, something like this:
if %day%==monday, tuesday, wednesday, thursday, friday (
goto yes
) else (
goto no
)
Now i know the first line won't work.
What i actually want to happen:
It automatticly checks which day it is. If it is Monday to Friday, it has to go to 'yes', otherwise (saturday/sunday) to 'no'.
How to do this?
Here is an example bat file that will do this sort of thing I am sure you can think of other ways to use this sample code. For instance anytime you need an "in" list. The tricky bit is the %date:~0,3% this says expand the %date% environment variable and starting at position 0 the beginning of the string return the next 3 characters. You can learn more about this from the "set /?" command.
example: IsWeekDay.bat
#echo off
setlocal
for %%i in (Mon,Tue,Wed,Thu,Fri) do (
if "%date:~0,3%"=="%%i" goto YES
)
:NO
echo No
goto EOF
:YES
echo Yes
:EOF
endlocal
I ran across this online. Tested, and it works. Returns the day as an integer, which you can still work with.
#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%
As Jay has mentioned, using date /t will only work on locales where this command outputs the day of week along with the date, and won't work on other locales (e.g. Russian). If you don't mind mixing your batch files with some VBScript, here's a solution that should work on all locales.
The trick is this tiny VBScript script that outputs the day of the week as a number (1 = Sunday, 2 = Monday, ... 7 = Saturday):
WScript.Echo DatePart("w", Date)
You can run this script from your batch file, read its output and apply your logic:
for /f %%d in ('cscript dayofweek.vbs //nologo') do (
if %%d==7 goto no :: Saturday
if %%d==1 goto no :: Sunday
)
goto yes
IF %day% == monday GOTO YES
IF %day% == tuesday GOTO YES
IF %day% == wednesday GOTO YES
IF %day% == thursday GOTO YES
IF %day% == friday GOTO YES
GOTO NO
I don't have the batch fu to answer the question as asked, but, assuming this is a Windows batch file, consider executing the script using the task scheduler, which will let you set the kind of schedule you're asking for.
Here is a batch file that extracts day-of-week, day, month and year in an almost locale-neutral way.
The only locale specific thing is the spelling of the day-of-week, the rest is locale neutral.
So in English, it will return Thu for Thursday, but in Dutch that will be do (for donderdag).
:: 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 date settings
::
:: 20110103 - adapted by jeroen#pluimers.com for Dutch locale
:: 20110303 - adapted by jeroen#pluimers.com for day-of-week
:: 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
::
:: Also, in Dutch, there is a difference between %date% and date/t: the former will not include
:: the day-of-the-week, but the latter will.
:: That means the if "%date%A" LSS "A" trick does not work with %date%, we need a loop
:: to check if the day-of-the-week needs us to take tokens 2-4 in stead of 1-3:
:: if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
:: for /f "tokens=1" %%t in ('date/t') do (...)
::
:: Another difference between Dutch and English is that the Dutch date/t will prepend the day of the week in a lower case 2-letter form.
:: So the LSS "A" trick needs to be replaced with an LSS "a" trick
:: if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
:: if "%%ta" LSS "a" (set toks=1-3) else (set toks=2-4)
::
:: 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_of_week=
set v_day=
set v_month=
set v_year=
SETLOCAL ENABLEEXTENSIONS
for /f "tokens=1" %%t in ('date/t') do (
set v_day_of_week=%%t
if "%%ta" 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 day_of_week=%v_day_of_week% & 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%
echo day of week=%day_of_week%
:EOF
Have fun with it!
--jeroen
From this answer, we have
wmic path win32_localtime get dayofweek
Expanding on this based on suggestions in this thread, we can set a dayofweek variable as follows:
#echo off
REM Unset dayofweek in case set in a previous execution of this batch file
set dayofweek=
REM Get dayofweek into a variable. Locale-specific: 0 is either Sunday or Monday.
for /F "skip=1 tokens=*" %%a in ('wmic path win32_localtime get dayofweek') do if not defined dayofweek set dayofweek=%%a
echo %dayofweek%
Note that 0 can be Sunday or Monday depending your locale.