Windows batch event reminder for next day - windows

How do I write a batch script, that would search in Dates.txt file of this format:
EventName1 : dd.mm.yyyy
EventName2 : dd.mm.yyyy
...
EventNameN : dd.mm.yyyy
for events with tomorrow's date, and if found, notify the user about them?
I was able to write a script for today's events:
#echo off
setlocal disableDelayedExpansion
IF NOT EXIST Dates.txt GOTO not_found_dates
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:~6,2%.%ldt:~4,2%.%ldt:~0,4%
echo Today: %ldt%
for /f "tokens=1,2 delims=:" %%A in (Dates.txt) do (
if "%%B"==" %ldt%" echo You have %%Atoday!
)
GOTO:EOF
:not_found_dates
echo Dates.txt not found!
GOTO:EOF
But I can't figure out how to find tomorrow's date to compare it with the dates in file.
Some help would be appreciated!

Well, I have finally figured it myself!
#echo off
setlocal DisableDelayedExpansion
if not exist Dates.txt goto not_found_dates
for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j
set d=%ldt:~6,2%
set m=%ldt:~4,2%
set y=%ldt:~0,4%
set ldt=%d%.%m%.%y%
echo ************************
echo * Today: %ldt% *
:loop
set /a d=1%d%-99
if %d% gtr 31 (
set d=1
set /a m=1%m%-99
if %m% gtr 12 (
set m=1
set /a y+=1
)
)
xcopy /d:%m%-%d%-%y% /l . .. >nul 2>&1 || goto loop
set td=0%d%
set td=%td:~-2%
set tm=0%m%
set tm=%tm:~-2%
set ty=%y%
set tomorrow=%td%.%tm%.%ty%
echo * Tomorrow: %tomorrow% *
echo ************************
for /f "tokens=1,2 delims=:" %%A in (Dates.txt) do (
if "%%B"==" %tomorrow%" echo # You have %%Atomorrow!
)
goto :EOF
:not_found_dates
echo Dates.txt not found!
goto :EOF
It works for the Dates.txt file, that uses dates in this format:
EventName1 : 31.05.2016
EventName2 : 30.05.2016
EventName3 : 31.05.2016
EventName4 : 01.06.2016
EventName5 : 31.05.2016
EventName6 : 02.06.2016
EventName7 : 01.06.2016
(Shouldn't forget about single empty spaces before and after colon, and about leading zeros for days and months that are less than 10.)
UPDATE:
At first, set /a d+=1 adds a day.
Then, this line:
xcopy /d:%m%-%d%-%y% /l . .. >nul 2>&1 || goto loop
checks if the date that was formed by set /a d+=1 part, actually exists in the calendar. If the date that was formed doesn't exist, it just "skips" the date, moving to the beginning of the loop to add one more day. This way, the date that doesn't exist can't be set as tomorrow's date.
The if %d% gtr 31 ( part is not doing anything unless it is actually 31st day of month today.
So, despite the if %d% gtr 31 ( part that looks somewhat confusing, this code still works well for months that have less than 31 days in them.
To understand it all better, turn #echo on and trace the changes in the date values.
For example, if we use:
set d=30
set m=04
set y=2016
Output is:
************************
* Today: 30.04.2016 *
* Tomorrow: 01.05.2016 *
************************
Also, for:
set d=28
set m=02
set y=2015
Output:
************************
* Today: 28.02.2015 *
* Tomorrow: 01.03.2015 *
************************

Here is a pure batch file solution to calculate tomorrow's date from current date with remarks explaining the code. The lines with remark command rem can be removed for faster processing the batch file by Windows command processor.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
if "%~1" == "" (
rem Get local date and time in a region independent format.
for /F "skip=1 tokens=1 delims=." %%D in ('%SystemRoot%\System32\wbem\wmic.exe OS get LocalDateTime') do set "LocalDateTime=%%D" & goto GetDate
) else (
rem This is for fast testing determining the date of tomorrow from any
rem date specified as parameter in format yyyyMMdd on calling this batch
rem file from within a command prompt window. The parameter string is
rem not validated at all as this is just for testing the code below.
set "LocalDateTime=%~1"
)
rem Get day, month and year from the local date/time string (or parameter).
:GetDate
set "Day=%LocalDateTime:~6,2%"
set "Month=%LocalDateTime:~4,2%"
set "Year=%LocalDateTime:~0,4%"
rem Define a variable with today's date in format dd.MM.yyyy
set "Today=%Day%.%Month%.%Year%"
rem Increase the day in month by 1 in any case.
rem It is necessary to remove leading 0 for the days 08 and 09 as
rem those two days would be otherwise interpreted as invalid octal
rem numbers and increment result would be 1 instead of 9 and 10.
rem if "%Day:~0,1%" == "0" set "Day=%Day:~1%"
rem set /A Day+=1
rem Faster is concatenating character 1 with the day string to string
rem representing 101 to 131 and subtract 99 to increment day by one.
set /A Day=1%Day%-99
rem The tomorrow's date is already valid if the day of month is less than 29.
if %Day% LSS 29 goto BuildTomorrow
rem Tomorrow is next month if day is equal (or greater) 32.
if %Day% GEQ 32 goto NextMonth
rem Day 31 in month is not possible in April, June, September and November.
rem In February it can't occur that day in month increased from 30 to 31
rem except on calling this batch file with invalid date string 20160230.
if %Day% EQU 31 (
if %Month% == 04 goto NextMonth
if %Month% == 06 goto NextMonth
if %Month% == 09 goto NextMonth
if %Month% == 11 goto NextMonth
)
rem The day 29 and 30 in month is valid for all months except February.
if NOT %Month% == 02 goto BuildTomorrow
rem Determine if this year is a leap year with 29 days in February.
set /A LeapYearRule1=Year %% 400
set /A LeapYearRule2=Year %% 100
set /A LeapYearRule3=Year %% 4
rem The current year is always a leap year if it can be divided by 400
rem with 0 left over (1600, 2000, 2400, ...). Otherwise if the current
rem year can be divided by 100 with 0 left over, the current year is NOT
rem a leap year (1900, 2100, 2200, 2300, 2500, ...). Otherwise the current
rem year is a leap year if the year can be divided by 4 with 0 left over.
rem Well, for the year range 1901 to 2099 just leap year rule 3 would be
rem enough and just last IF condition would be enough for this year range.
set "LastFebruaryDay=28"
if %LeapYearRule1% == 0 (
set "LastFebruaryDay=29"
) else if NOT %LeapYearRule2% == 0 (
if %LeapYearRule3% == 0 (
set "LastFebruaryDay=29"
)
)
if %Day% LEQ %LastFebruaryDay% goto BuildTomorrow
rem Tomorrow is next month. Therefore set day in month to 1, increase the
rem month by 1 and if now greater than 12, set month to 1 and increase year.
:NextMonth
set "Day=1"
set /A Month=1%Month%-99
if %Month% GTR 12 (
set "Month=1"
set /A Year+=1
)
rem The leading 0 on month and day in month could be removed and so both
rem values are defined again as string with a leading 0 added and next just
rem last two characters are kept to get day and month always with two digits.
:BuildTomorrow
set "Day=0%Day%"
set "Day=%Day:~-2%"
set "Month=0%Month%"
set "Month=%Month:~-2%"
rem Define a variable with tomorrow's date in format dd.MM.yyyy
set "Tomorrow=%Day%.%Month%.%Year%"
echo Today is: %Today%
echo Tomorrow is: %Tomorrow%
endlocal
Please read my answer on Why does %date% produce a different result in batch file executed as scheduled task? It explains in full details the FOR command line using WMIC to get current date in region independent format.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
echo /?
endlocal /?
for /?
goto /?
if /?
rem /?
set /?
setlocal /?
wmic OS get /?

Related

Subtract month in Windows batch

I would like to have this run and show the previous month. When I try to subtract the month it makes the last day of the month field not appear.
#echo off
set FirstDay=01
set Month=%date:~4,2%
set Year=%date:~10,4%
if %Month%==01 set LastDay=31 & goto foundate
if %Month%==02 set LastDay=28 & goto foundate
if %Month%==03 set LastDay=31 & goto foundate
if %Month%==04 set LastDay=30 & goto foundate
if %Month%==05 set LastDay=31 & goto foundate
if %Month%==06 set LastDay=30 & goto foundate
if %Month%==07 set LastDay=31 & goto foundate
if %Month%==08 set LastDay=31 & goto foundate
if %Month%==09 set LastDay=30 & goto foundate
if %Month%==10 set LastDay=31 & goto foundate
if %Month%==11 set LastDay=30 & goto foundate
if %Month%==12 set LastDay=31 & goto foundate
:foundate
echo The year is: %Year%
echo The month is: %Month%
echo First day of this month is: %FirstDay%
echo Last day of this month is: %LastDay%
Dates are complicated to work with and easy to get wrong, and if you can avoid rolling your own, do so.
CMD does not come with a native date library, but the .NET System.DateTime library is available via PowerShell. The following PS script shows how to use .NET to do what you're asking.
Get-LastMonthStats.ps1
$lastmonth = (Get-Date).addMonths(-1)
"The year is $($lastmonth.year)"
"The month is $($lastmonth.Month)"
"First day of this month is 01"
"Last day of this month is $([DateTime]::DaysInMonth($lastmonth.year, $lastmonth.month))"
Nearly all of this script is formatting the output. To run from CMD, launch this with the command
powershell.exe -ex bypass -f Get-LastMonthStats.ps1
Alternatively, you can put the whole script on one (very long) command line, if you don't want to create a separate .ps1 file.
powershell -c "$lastmonth = (Get-Date).addMonths(-1); 'The year is ' + $lastmonth.year; 'The month is ' + $lastmonth.Month; 'First day of this month is 01'; 'Last day of this month is ' + [DateTime]::DaysInMonth($lastmonth.year, $lastmonth.month)"
I made a function library that has these functions. Doing what you want with this library is easy, check below.
The functions are at the end of the code. Just copy to the end of your file (after a goto:eof) and call them using specified arguments.
The given code inside :main should do what you are asking for.
Remarks:
Has inbuilt Leap Year check, so if the year is a Leap Year, Februrary will return 29 days.
When copying functions to your file, please keep Author information
Code:
#echo off
:main
:: Recommended to use GetDateIntl function, to get region-independent results (Check functions at the end of this file)
call :GetDateIntl Year Month Day /A
echo/Using GetDateIntl to get current date: %Year%-%Month%-%day%
echo/
:: Call function to get last day of this month (Check functions at the end of this file)
call :GetLastDayOfMonth %Month% %Year% LastDay
echo This month is: %Month%/%Year%
echo First day of any month is always 1
echo Last day of this month is: %LastDay%
echo/
:: Get previous month number
set /A "PMonth= %Month% - 1"
set "PYear=%Year%"
:: Correct PMonth and PYear if this month is December
if %PMonth%==0 ( set "PMonth=12" & set /A "PYear= %PYear% - 1" )
:: Call function to get last day of previous month (Check function after :main)
call :GetLastDayOfMonth %PMonth% %PYear% PLastDay
echo Previous month is: %PMonth%/%PYear%
echo Last day of previous month is: %PLastDay%
goto:eof
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:GetDateIntl yy mm dd [/A]
:: Returns the current date on any machine with regional-independent settings
:: Arguments:
:: yy = variable name for the year output
:: mm = variable name for the month output
:: dd = variable name for the day output
:: /A = OPTIONAL, removes leading 0 on days/months smaller than 10
::
:: By Cyberponk, v1.1 - 11/05/2016
:: v1.0 - 2015
::
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'%"=="" set 'yy'=%'aa'%
if %'yy'% LSS 100 set 'yy'=20%'yy'%
endlocal&set %1=%'yy'%&set %4 %2=%'mm'%&set %4 %3=%'dd'%&goto :EOF
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:IsLeapYear %year% IsLeap
:: Checks if a year is a Leap Year (year that has 366 days)
:: Arguments:
:: %year% = year number input. Can be a number or a variable containing a 4 digit number
:: IsLeap = result output containing 1 or 0 (1= is leap year, 0= not yeap lear)
::
:: By Cyberponk, v1.1 - 11/05/2016
::
SETLOCAL ENABLEEXTENSIONS
set /A "IsLeap=(!(%1 %% 4) & !!(%1 %% 100)) | !(%1 %% 400)"
endlocal & set %2=%IsLeap%& goto:EOF
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:GetLastDayOfMonth %month% %year% LastDay
:: Gets the last day of a given month from a given year
:: Arguments:
:: %month% = month number input. Can be a number or a variable containing a number
:: %year% = year for reference (used to check for leap years)
:: LastDay = result output containing last day of the specified month
::
:: By Cyberponk, v1.0 - 11/05/2016
::
SETLOCAL ENABLEEXTENSIONS
:: Mathematical formula to last day of month
set /A "LastDay= 28 + (%1 + (%1/8)) %% 2 + 2 %% %1 + 2 * (1/%1)
:: Add 1 day if year is a Leap Year and month is February
call :IsLeapYear %2 IsLeap
if %LastDay%==28 set /A LastDay=%LastDay% + %IsLeap%
endlocal & set %3=%LastDay%& goto:EOF
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
here's a piece of code that will get the previous month:
#echo off
for /f "" %%# in ('WMIC Path Win32_LocalTime Get month /format:value') do (
for /f %%Z in ("%%#") do set /a %%Z-1
)
if %month% equ 0 set month=12
echo %month%
Better use wmic to get the date parts because it's independent from the machine's date format unlike the %date% variable.
EDIT (as requested in the comments) :
#echo off
setlocal disableDelayedExpansion
for /f "" %%# in ('"WMIC Path Win32_LocalTime Get month,year /format:value"') do (
for /f %%Z in ("%%#") do set "%%Z"
)
set /a month=month-1
if %month% equ 0 set month=12
rem echo %month% -- %year%
set /A "leap=!(year&3) + (!!(year%%100)-!!(year&15))"
if %leap% equ 0 (set "m2=29") else (set "m2=28")
setlocal enableDelayedExpansion
set m1=31
set m3=31
set m4=30
set m5=31
set m6=30
set m7=31
set m8=31
set m9=30
set m10=31
set m11=30
set m12=31
set premonLastDay=!m%month%!
endlocal & set premonLastDay=%premonLastDay%
if %month% equ 12 (
set /a year=year-1
)
echo %premonLastDay%-%month%-%year%
endlocal
I've modified script of cyberponk for following error
Previous month is: -1/2020
after
if "%'yy'%"=="" set 'yy'=%'aa'%
I've added as fix
if %'mm'% LSS 10 set 'mm'=%'mm':~1,1%

How to get the day of year in a batch file

How can I get the day of year from the current date in a Windows batch file?
I have tried
SET /A dayofyear=(%Date:~0,2%*30.5)+%Date:~3,2%
But it does not work with leap years, and it is always off by a few days. I would not like to use any third-party executables.
If you want the Julian Day Number, you may use the method posted in my accepted answer given at previous link. However, the "day of year" is just a number between 1 and 365 (366 for leap years). The Batch file below correctly calculate it:
#echo off
setlocal EnableDelayedExpansion
set /A i=0, sum=0
for %%a in (31 28 31 30 31 30 31 31 30 31 30 31) do (
set /A i+=1
set /A accum[!i!]=sum, sum+=%%a
)
set /A month=1%Date:~0,2%-100, day=1%Date:~3,2%-100, yearMOD4=%Date:~6,4% %% 4
set /A dayOfYear=!accum[%month%]!+day
if %yearMOD4% equ 0 if %month% gtr 2 set /A dayOfYear+=1
echo %dayOfYear%
Note: This relies on the date format MM/DD/YYYY.
EDIT 2020/08/10: Better method added
I modified the method so it now uses wmic to get the date. The new method is also shorten, but no simpler! ;):
#echo off
setlocal
set "daysPerMonth=0 31 28 31 30 31 30 31 31 30 31 30"
for /F "tokens=1-3" %%a in ('wmic Path Win32_LocalTime Get Day^,Month^,Year') do (
set /A "dayOfYear=%%a, month=%%b, leap=!(%%c%%4)*(((month-3)>>31)+1)" 2>NUL
)
set /A "i=1, dayOfYear+=%daysPerMonth: =+(((month-(i+=1))>>31)+1)*%+leap"
echo %dayOfYear%
#Aacini's answer has got two weak points (although it suffices for many applications, and it is a great approach after all!):
the retrieved system date relies on format MM/DD/YYYY, but %Date% is locale-dependent;
the calculation does not fully comply with the definition of leap years (see this article);
The following is a revised version of #Aacini's batch script (described within explanatory remarks):
#echo off
setlocal EnableDelayedExpansion
set /A i=0, sum=0
rem accumulate day-offsets for every month in %accum[1...12]%
for %%a in (31 28 31 30 31 30 31 31 30 31 30 31) do (
set /A i+=1
set /A accum[!i!]=sum, sum+=%%a
)
rem check for availability of alternative date value given via (1st) command line argument,
rem just for convenient batch testing
if "%1"=="" (
rem WMIC retrieves current system date/time in standardised format;
rem parse its output by FOR /F, then store it in %CurrDate%
for /F "tokens=2 delims==" %%D in ('wmic OS GET LocalDateTime /VALUE ^| find "="') do (
set CurrDate=%%D
)
) else (
rem apply date value from command line in YYYYMMDD format (not checked for validity)
set CurrDate=%1
)
rem extract %month% and %day%;
set /A month=1%CurrDate:~4,2%-100, day=1%CurrDate:~6,2%-100
rem compute several moduli needed for determining whether year is leap year
set /A yearMOD4=%CurrDate:~0,4% %% 4
set /A yearMOD100=%CurrDate:~0,4% %% 100, yearMOD400=%CurrDate:~0,4% %% 400
rem calculate %dayOfYear% as it were not a leap year
set /A dayOfYear=!accum[%month%]!+day
rem adapt %dayOfYear% only in case %month% is past February (29th)
if %month% gtr 2 (
rem check for leap year and adapt %dayOfYear% accordingly
if %yearMOD4% equ 0 set /A dayOfYear+=1
if %yearMOD400% neq 0 if %yearMOD100% equ 0 set /A dayOfYear-=1
)
rem compound statement to let %dayOfYear% survive SETLOCAL/ENDLOCAL block
endlocal & set dayOfYear=%dayOfYear%
rem return result
echo %dayOfYear%
This use the laps years in editable in loop | for /l %%L in (2020 4 2100) | < or more!
#echo off & setlocal enabledelayedexpansion && set "_cmd=Get Day^,Month^,Year^"
for /l %%L in (2020 4 2100)do set "_array_leap_year_=!_array_leap_year_!%%L,"
for /f "tokens=1-3delims= " %%a in ('wmic Path Win32_LocalTime !_cmd! ^| findstr /r "[0-9]"')do (
set "_yy=%%c" & set "_mm=0%%b" & set "_dd=0%%a" && set "_mm=!_mm:~-2!" & set "_dd=!_dd:~-2!" & set _date=!_yy!_!_mm!_!_dd!)
echo/!_array_leap_year_!|findstr /lic:"!_date:~0,4!," >nul&&(set "_leap_=29" & set "_year_=366")||(set "_leap_=28" & set "_year_=365")
set "_mm_dd_year_=01-31,02-!_leap_!,03-31,04-30,05-31,06-30,07-31,08-31,09-30,10-31,11-30,12-31" && set /a "_cnt=0" & set /a "_loop=!_mm! * 6"
(for /l %%d in (0 6 !_loop!)do set "_sum=!_mm_dd_year_:~%%d,5!" & if "9!_sum:~,2!" lss "9!_mm!" set /a "_day_year_+=!_sum:~-2!")
set /a "_day_year_+=!_dd!" && set /a "_remain=!_day_year_! - !_year_!" && echo/Today: !_date! ^| Day of Year: !_day_year_! ^| Days Remaining: !_remain:-=!
| Result | Today: 2019_04_21 | Day of Year: 111 | Days Remaining: 254
Conventional formatting:
#echo off & setlocal enabledelayedexpansion
set "_cmd=Get Day^,Month^,Year^"
for /l %%L in (2020 4 2100)do set "_array_leap_year_=!_array_leap_year_!%%L,"
for /f "tokens=1-3delims= " %%a in ('wmic Path Win32_LocalTime !_cmd! ^| findstr /r "[0-9]"')do (
set "_yy=%%c"
set "_mm=0%%b"
set "_dd=0%%a"
set "_mm=!_mm:~-2!"
set "_dd=!_dd:~-2!"
set _date=!_yy!_!_mm!_!_dd!
)
echo/!_array_leap_year_!|findstr /lic:"!_date:~0,4!," >nul && (
set "_leap_=29" & set "_year_=366" )||( set "_leap_=28" & set "_year_=365" )
set "_mm_dd_year_=01-31,02-!_leap_!,03-31,04-30,05-31,06-30,07-31,08-31,09-30,10-31,11-30,12-31"
set /a "_loop=!_mm! * 6"
for /l %%d in (0 6 !_loop!)do set "_sum=!_mm_dd_year_:~%%d,5!" && (
if "9!_sum:~,2!" lss "9!_mm!" set /a "_day_year_+=!_sum:~-2!" )
set /a "_day_year_+=!_dd!"
set /a "_remain=!_day_year_! - !_year_!"
echo/Today: !_date! ^| Day of Year: !_day_year_! ^| Days Remaining: !_remain:-=!

In a batch file, how would I check if today's date is after a set date?

I'm trying to check if today's date is after a certain date so that I can make a batch file that will only run after a certain date.
Right now I have:
#ECHO off
IF %date% GTR 24/01/2015(
ECHO it is after 24/01/2015
)
pause
But that doesn't work.
In order to compare the dates you need to strip out the individual components of the current date and then put them back together into a comparable format (YYYY-MM-DD):
#ECHO OFF
SET FirstDate=2015-01-24
REM These indexes assume %DATE% is in format:
REM Abr MM/DD/YYYY - ex. Sun 01/25/2015
SET TodayYear=%DATE:~10,4%
SET TodayMonth=%DATE:~4,2%
SET TodayDay=%DATE:~7,2%
REM Construct today's date to be in the same format as the FirstDate.
REM Since the format is a comparable string, it will evaluate date orders.
IF %TodayYear%-%TodayMonth%-%TodayDay% GTR %FirstDate% (
ECHO Today is after the first date.
) ELSE (
ECHO Today is on or before the first date.
)
#if (#X)==(#Y) #end /* JScript comment
#echo off
set "comp_date=2015/1/20"
rem :: the first argument is the script name as it will be used for proper help message
for /f %%# in ('cscript //E:JScript //nologo "%~f0" "%comp_date%"') do set comp=%%#
if %comp% EQU -1 (
echo current date is bigger than %comp_date%
) else (
echo current date is less than %comp_date%
)
exit /b %errorlevel%
#if (#X)==(#Y) #end JScript comment */
var ARGS = WScript.Arguments;
var compdate=ARGS.Item(0);
var c_date=(new Date()).getTime();
var comp_date=(new Date(compdate)).getTime();
//WScript.Echo(c_date);
//WScript.Echo(comp_date);
WScript.Echo(comp_date<c_date);
#ECHO OFF
SETLOCAL
CALL :CONVERT date1 24/01/2015
CALL :CONVERT date2 %DATE%
IF %date1% gtr %date2% (ECHO earlier) ELSE (ECHO same or later)
GOTO :EOF
:CONVERT
FOR /f "tokens=1,2,3 delims=/-. " %%a IN ("%2") DO SET /a %1=%%c0000+1%%b00+1%%a-10100
GOTO :eof
But - this method will only work for date formats where the day number and month number are two digits.
I use dd/mm/yyyy for my date format. This will work as written for dd/mm/yy or dd/mm/yyyy with separators of /-. or space
If your date format has a 3-character dayname prefix, then use %date:~4% in place of %date%
I'd use wmic os get localdatetime and compare YYYYMMDD.
#echo off
setlocal
for /f "tokens=2 delims==" %%I in (
'wmic os get localdatetime /format:list ^| find "="'
) do set "now=%%I"
if %now:~0,8% gtr 20150124 (
echo It's time.
)
Then you're just comparing 8-digit integers and should get the results you expect. I'm unable to test this at the moment as I'm posting from my phone, but I don't see why it wouldn't work.
The first thing you'll want to do is open the Command Prompt. Then type the following command (and press Enter):
ECHO %DATE%
The output will probably be an abbreviated weekday name followed by the current date in the format for your locale. It may even omit the day of the week entirely.
Now just make a new text file with the extension BAT or CMD and paste in the following script. Then configure it according to the remarks (preceded by the command REM).
#ECHO OFF
SETLOCAL ENABLEEXTENSIONS
REM -- 2 digit day
SET "_day=%DATE:~-10,2%" & REM day goes first (dd/mm/yyyy); if not, remove this line
SET "_day=%DATE:~-7,2%" & REM day goes second (mm/dd/yyyy); if not, remove this line
REM -- 2 digit month
SET "_month=%DATE:~-10,2%" & REM month goes first (mm/dd/yyyy); if not, remove this line
SET "_month=%DATE:~-7,2%" & REM month goes second (dd/mm/yyyy); if not, remove this line
REM -- 4 digit year
SET "_year=%DATE:~-10,4%" & REM year goes first (yyyy/##/##); if not, remove this line
SET "_year=%DATE:~-4%" & REM year goes last (##/##/yyyy); if not, remove this line
REM -- The variables below are set to year-month-day without separators (yyyymmdd)
SET "today=%_year%%_month%%_day%" & REM today's date based on your selections above
SET "compareDate=20180727" & REM the date you are comparing with today
REM -- Here's where the magic happens with comparing the two dates
IF %compareDate% LSS %today% ECHO The comparison date is in the past.
IF %compareDate% EQU %today% ECHO The comparison date is today.
IF %compareDate% GTR %today% ECHO The comparison date is in the future.
GOTO :EOF

Windows Batch File not Validating Year

So I have a windows batch script that validates to see if the date format I entered is in the correct format. Everything is working fine with it except when it gets to the year part of it. It doesn't seem to validate the year in the correct format of xxxx. It will accept any number. Where is it breaking, I can't tell? Fix suggestions? Thank you!
set i=0
for %%a in (31 28 31 30 31 30 31 31 30 31 30 31) do (
set /A i+=1
set dpm[!i!]=%%a
)
set /P "inDate=Please insert FNOL date (MM-DD-YYYY format): "
if "%inDate:~2,1%%inDate:~5,1%" neq "--" goto invalidDate
for /F "tokens=1-3 delims=-" %%a in ("%inDate%") do set "MM=%%a" & set "DD=%%b" & set "YYYY=%%c"
ver > NUL
set /A month=1%MM%-100, day=1%DD%-100, year=1%YYYY%-10000, leap=year%%4
if errorlevel 1 goto invalidDate
if not defined dpm[%month%] goto invalidDate
if %leap% equ 0 set dpm[2]=29
if %day% gtr !dpm[%month%]! goto invalidDate
if %day% lss 1 goto invalidDate
SET fnoldate=%YYYY%-%MM%-%DD%
ECHO.
SET /P confirmdate=You entered a FNOL date of "%fnoldate%". Is this correct? [y/n]
ECHO.
You're missing some components of your batch file.
At the top, you should have the following:
#Echo Off
SetLocal EnableDelayedExpansion
Your code has some GoTo references, but it can't go anywhere. You should add the following at the bottom:
GoTo :EOF
:invalidDate
echo Invalid date.
Hmm. Giving an example of a failure would have been useful.
Let's take an 'invalid' year like 14.
Your calculation for 01-01-14 would be year=114-10000
You really need to check that year has length 4 first.
if "%year:~3%=="" goto invaliddate
if not "%year:~4%=="" goto invaliddate
and you are not then checking after year-is-numeric for year in a valid range
Here is a method to validate the year:
#echo off
set year=1980
for /f "delims=1234567890" %%a in ("%year%") do echo you must enter numeric characters only & goto :EOF
if %year% GEQ 1800 if %year% LEQ 2014 (
echo year is between 1800 and 2014
) else (
echo enter a year between 1800 and 2014
)

Setting a windows batch file variable to the day of the week

I have a windows batch file that runs daily. Wish to log data into a file and want to rotate it (i.e. having at most the last 7 days worth of data).
Looked into the commands DATE and DELIMS - Cannot figure out a solution.
Is there a simple solution to create a file name that contains the day of the week i.e. 0 for monday etc.
Or do I have to resort to some better shell script.
%DATE% is not your friend. Because the %DATE% environment variable (and the DATE command) returns the current date using the Windows short date format that is fully and endlessly customizable. One user may configure the system to return 07/06/2012 while another might choose Fri060712. Using %DATE% is a complete nightmare for a BAT programmer.
There are two possible approaches to solve this problem:
You may be tempted to temporarily change the short date format, by changing the locale settings in the registry value HKCU\Control Panel\International\sShortDate, to your recognizable format. Then access %DATE% to get the date in the format you want; and finally restore the format back to the original user format. Something like this
reg copy "HKCU\Control Panel\International" "HKCU\Control Panel\International-Temp" /f >nul
reg add "HKCU\Control Panel\International" /v sShortDate /d "ddd" /f >nul
set DOW=%DATE%
reg copy "HKCU\Control Panel\International-Temp" "HKCU\Control Panel\International" /f >nul
but this method has two problems:
it tampers with a global registry value for its local particular purpouses, so it may interfere with other processes or user tasks that at the very same time query the date in short date format, including itself if run simultaneously.
and it returns the three letter day of the week in the local language that may be different in different systems or different users.
use WMIC Win32_LocalTime, that returns the date in a convenient way to directly parse it with a FOR command.
FOR /F "skip=1" %%A IN ('WMIC Path Win32_LocalTime Get DayOfWeek' ) DO (
set DOW=%%A
)
this is the method I recommend.
few more ways:
1.Robocopy not available in XP but can be downloaded form with win 2003 resource tool kit .Also might depend on localization:
#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%
endlocal
2.MAKECAB - works on every windows machine (but creates a small temp file).Function provided by carlos:
#Echo Off
Call :GetDate.Init
Rem :GetDate.Init should be called one time in the code before call to :Getdate
Call :GetDate
Echo weekday:%weekday%
Goto :EOF
:GetDate.Init
Set /A "jan=1,feb=2,mar=3,apr=4,may=5,jun=6,jul=7,aug=8,sep=9,oct=10,nov=11,dec=12"
Set /A "mon=1,tue=2,wed=3,thu=4,fri=5,sat=6,sun=7"
(
Echo .Set InfHeader=""
Echo .Set InfSectionOrder=""
Echo .Set InfFooter="%%2"
Echo .Set InfFooter1=""
Echo .Set InfFooter2=""
Echo .Set InfFooter3=""
Echo .Set InfFooter4=""
Echo .Set Cabinet="OFF"
Echo .Set Compress="OFF"
Echo .Set DoNotCopyFiles="ON"
Echo .Set RptFileName="NUL"
) >"%Temp%\~foo.ddf"
Goto :Eof
:GetDate
Set "tf=%Temp%\~%random%"
Makecab /D InfFileName="%tf%" /F "%Temp%\~foo.ddf" >NUL
For /F "usebackq tokens=1-7 delims=: " %%a In ("%tf%") Do (
Set /A "year=%%g,month=%%b,day=1%%c-100,weekday=%%a"
Set /A "hour=1%%d-100,minute=1%%e-100,second=1%%f-100")
Del "%tf%" >NUL 2>&1
Goto :Eof
3.W32TM - uses command switches introduced in Vista so will not work on windows 2003/XP:
#echo off
setlocal
call :w32dow day_ow
echo %day_ow%
pause
exit /b 0
endlocal
:w32dow [RrnVar]
setlocal
rem :: prints the day of the week
rem :: works on Vista and above
rem :: getting ansi date ( days passed from 1st jan 1601 ) , timer server hour and current hour
FOR /F "tokens=4,5 delims=:( " %%D in ('w32tm /stripchart /computer:localhost /samples:1 /period:1 /dataonly /packetinfo^|find "Transmit Timestamp:" ') do (
set "ANSI_DATE=%%D"
set "TIMESERVER_HOURS=%%E"
)
set "LOCAL_HOURS=%TIME:~0,2%"
if "%TIMESERVER_HOURS:~0,1%0" EQU "00" set TIMESERVER_HOURS=%TIMESERVER_HOURS:~1,1%
if "%LOCAL_HOURS:~0,1%0" EQU "00" set LOCAL_HOURS=%LOCAL_HOURS:~1,1%
set /a OFFSET=TIMESERVER_HOURS-LOCAL_HOURS
rem :: day of the week will be the modulus of 7 of local ansi date +1
rem :: we need need +1 because Monday will be calculated as 0
rem :: 1st jan 1601 was Monday
rem :: if abs(offset)>12 we are in different days with the time server
IF %OFFSET%0 GTR 120 set /a DOW=(ANSI_DATE+1)%%7+1
IF %OFFSET%0 LSS -120 set /a DOW=(ANSI_DATE-1)%%7+1
IF %OFFSET%0 LEQ 120 IF %OFFSET%0 GEQ -120 set /a DOW=ANSI_DATE%%7+1
rem echo Day of the week: %DOW%
endlocal & if "%~1" neq "" (set "%~1=%DOW%") else echo %DOW%
4..bat/jscript hybrid (must be saved as .bat):
#if (#x)==(#y) #end /***** jscript comment ******
#echo off
for /f %%d in ('cscript //E:JScript //nologo "%~f0"') do echo %%d
exit /b 0
***** end comment *********/
WScript.Echo((new Date).getDay());
5..bat/vbscript hybrid (must be saved as .bat)
:sub echo(str) :end sub
echo off
'>nul 2>&1|| copy /Y %windir%\System32\doskey.exe '.exe >nul
'& echo/
'& for /f %%w in ('cscript /nologo /E:vbscript %~dpfn0') do echo day of the week %%w
'& echo/
'& del /q "'.exe" >nul 2>&1
'& exit /b
WScript.Echo Weekday(Date)
WScript.Quit
6.powershell can be downloaded from microsoft.Available by default in everything form win7 and above:
#echo off
setlocal
for /f %%d in ('"powershell (Get-Date).DayOfWeek.Value__"') do set dow=%%d
echo day of the week : %dow%
endlocal
7.WMIC already used as an answer but just want to have a full reference.And with cleared <CR>:
#echo off
setlocal
for /f "delims=" %%a in ('wmic path win32_localtime get dayofweek /format:list ') do for /f "delims=" %%d in ("%%a") do set %%d
echo day of the week : %dayofweek%
endlocal
9.Selfcompiled jscript.net (must be saved as .bat):
#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.NET\Framework\"
:: searching the latest installed .net framework
for /f "tokens=* delims=" %%v in ('dir /b /s /a:d /o:-n "%SystemRoot%\Microsoft.NET\Framework\v*"') do (
if exist "%%v\jsc.exe" (
rem :: the javascript.net compiler
set "jsc=%%~dpsnfxv\jsc.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.DayOfWeek);
#ECHO OFF
REM GET DAY OF WEEK VIA DATE TO JULIAN DAY NUMBER CONVERSION
REM ANTONIO PEREZ AYALA
REM GET MONTH, DAY, YEAR VALUES AND ELIMINATE LEFT ZEROS
FOR /F "TOKENS=1-3 DELIMS=/" %%A IN ("%DATE%") DO SET /A MM=10%%A %% 100, DD=10%%B %% 100, YY=%%C
REM CALCULATE JULIAN DAY NUMBER, THEN DAY OF WEEK
IF %MM% LSS 3 SET /A MM+=12, YY-=1
SET /A A=YY/100, B=A/4, C=2-A+B, E=36525*(YY+4716)/100, F=306*(MM+1)/10, JDN=C+DD+E+F-1524
SET /A DOW=(JDN+1)%%7
DOW is 0 for Sunday, 1 for Monday, etc.
I thought that my first answer gives the correct day of week as a number between 0 and 6. However, because you had not indicated why this answer does not give the result you want, I can only guess the reason.
The Batch file below create a log file each day with a digit in the name, 0=Sunday, 1=Monday, etc... The program assume that echo %date% show the date in MM/DD/YYYY format; if this is not the case, just change the position of mm and dd variables in the for command.
#echo off
for /F "tokens=1-3 delims=/" %%a in ("%date%") do set /A mm=10%%a %% 100, dd=10%%b %% 100, yy=%%c
if %mm% lss 3 set /A mm+=12, yy-=1
set /A a=yy/100, b=a/4, c=2-a+b, e=36525*(yy+4716)/100, f=306*(mm+1)/10, dow=(c+dd+e+f-1523)%%7
echo Today log data > Day-%dow%.txt
If this is not what you want, please indicate the problem so I can fix it.
EDIT: The version below get date parts independent of locale settings:
#echo off
for /F "skip=1 tokens=2-4 delims=(-/)" %%A in ('date ^< NUL') do (
for /F "tokens=1-3 delims=/" %%a in ("%date%") do (
set %%A=%%a
set %%B=%%b
set %%C=%%c
)
)
set /A mm=10%mm% %% 100, dd=10%dd% %% 100
if %mm% lss 3 set /A mm+=12, yy-=1
set /A a=yy/100, b=a/4, c=2-a+b, e=36525*(yy+4716)/100, f=306*(mm+1)/10,
dow=(c+dd+e+f-1523)%%7
echo Today log data > Day-%dow%.txt
EDIT: The version below insert day of week as 3-letter short name:
#echo off
for /F "skip=1 tokens=2-4 delims=(-/)" %%A in ('date ^< NUL') do (
for /F "tokens=1-3 delims=/" %%a in ("%date%") do (
set %%A=%%a
set %%B=%%b
set %%C=%%c
)
)
set /A mm=10%mm% %% 100, dd=10%dd% %% 100
if %mm% lss 3 set /A mm+=12, yy-=1
set /A a=yy/100, b=a/4, c=2-a+b, e=36525*(yy+4716)/100, f=306*(mm+1)/10,
dow=(c+dd+e+f-1523)%%7 + 1
for /F "tokens=%dow%" %%a in ("Sun Mon Tue Wed Thu Fri Sat") do set dow=%%a
echo Today log data > Day-%dow%.txt
Regards,
Antonio
This turned out way more complex then I first suspected, and I guess that's what intrigued me, I searched every where and all the methods given wouldnt work on Windows 7.
So I have an alternate solution which uses a Visual Basic Script.
The batch creates and executes the script(DayOfWeek.vbs), assigns the scripts output (Monday, Tuesday etc) to a variable (dow), the variable is then checked and another variable (dpwnum) assigned with the days number, afterwards the VBS is deleted hope it helps:
#echo off
REM Create VBS that will get day of week in same directory as batch
echo wscript.echo WeekdayName(Weekday(Date))>>DayOfWeek.vbs
REM Cycle through output to get day of week i.e monday,tuesday etc
for /f "delims=" %%a in ('cscript /nologo DayOfWeek.vbs') do #set dow=%%a
REM delete vbs
del DayOfWeek.vbs
REM Used for testing outputs days name
echo %dow%
REM Case of the days name is important must have a capital letter at start
REM Check days name and assign value depending
IF %dow%==Monday set downum=0
IF %dow%==Tuesday set downum=1
IF %dow%==Wednesday set downum=2
IF %dow%==Thursday set downum=3
IF %dow%==Friday set downum=4
IF %dow%==Saturday set downum=5
IF %dow%==Sunday set downum=6
REM print the days number 0-mon,1-tue ... 6-sun
echo %downum%
REM set a file name using day of week number
set myfile=%downum%.bak
echo %myfile%
pause
exit
EDIT:
Though I turned to VBS, It can be done in pure batch, took me a while to get it working and a lot of searching lol, but this seems to work:
#echo off
SETLOCAL enabledelayedexpansion
SET /a count=0
FOR /F "skip=1" %%D IN ('wmic path win32_localtime get dayofweek') DO (
if "!count!" GTR "0" GOTO next
set dow=%%D
SET /a count+=1
)
:next
echo %dow%
pause
The only caveat for you on the above batch is that its day of weeks are from 1-7 and not 0-6
This works for me
FOR /F "tokens=3" %%a in ('robocopy ^|find "Started"') DO SET TODAY=%%a
I am in the US. I can run this code in Windows 7, Windows 2008 R2, Windows Server 2003, Windows XP (All OS's are current with Windows Updates and patches). All with short date setting without ddd (or dddd) (day of week).
#echo off
for /f %%a in ('date /t') do set DAY=%%a
echo.
echo The Day Is: %DAY%
echo.
If today is Thursday, it would output "The Day Is: Thu".
This returns the day on all 4 Windows versions I have tested on. And only the day. When I changed my short date setup to be "ddd, M/d/yyyy", my output would show the day with a comma (e.g. Thu,) which tells me this code does use the short date format. But what also may be happening is that if the short date does not contain the day of week, it may look to the long date format which on all 4 machines I tested on, have dddd in the format.
This is not my work (well, I modified it slightly from the example), and it's late to the game, but this works on Server 2003 for me;
#echo off
set daysofweek=Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday
for /F "skip=2 tokens=2-4 delims=," %%A in ('WMIC Path Win32_LocalTime Get DayOfWeek /Format:csv') do set daynumber=%%A
for /F "tokens=%daynumber% delims=," %%B in ("%daysofweek%") do set day=%%B
Citation: TechSupportForum
First - Copy CON SETUPDAY.001
SET WORKDAY=^Z (very important - no cr/lf)
DATE /T >SETUPDAY.002
COPY SETUPDAY.001+SETUPDAY.002 NEWDAY.BAT >nul
CALL NEWDAY.BAT
SET WEEKDAY=%WORKDAY:~0,3%
SET MDY=%WORKDAY:~4,10%
USE %WEEKDAY% IN YOUR SCRIPT
Locale-dependent version: In some environments, the following will extract the day name from the date:
set dayname=%date:~0,3%
It assumes that the day name is the first part of %date%. Depending on the machine settings, though, the substring part (~0,3) would need to change.
A statement such as this would dump to a file with a three character day name:
set logfile=%date:~0,3%.log
echo some stuff > %logfile%
Locale-independent version: If you need it less dependent on the current machine's day format, another way of doing it would be to write a tiny application that prints the day of the week. Then use the output of that program from the batch file. For example, the following C application prints dayN where N=0..6.
#include <stdio.h>
#include <time.h>
int main( int argc, char* argv[] )
{
time_t curtime;
struct tm * tmval;
time( &curtime );
tmval = localtime( &curtime );
// print dayN. Or use a switch statement and print
// the actual day name if you want
printf( "day%d", tmval->tm_wday );
}
If the above were compiled and linked as myday.exe, then you could use it from a batch file like this:
for /f %%d in ('myday.exe') do set logfile=%%d.log
echo some stuff > %logfile%
I have this solution working for me:
Create a file named dayOfWeek.vbs in the same dir where the cmd file will go.
dayOfWeek.vbs contains a single line:
wscript.stdout.write weekdayname(weekday(date))
or, if you want day number instead of name:
wscript.stdout.write weekday(date)
The cmd file will have this line:
For /F %%A In ('CScript dayOfWeek.vbs //NoLogo') Do Set dayName=%%A
Now you can use variable dayName like:
robocopy c:\inetpub \\DCStorage1\Share1\WebServer\InetPub_%dayName% /S /XD history logs
Another spin on this topic. The below script displays a few days around the current, with day-of-week prefix.
At the core is the standalone :dpack routine that encodes the date into a value whose modulo 7 reveals the day-of-week per ISO 8601 standards (Mon == 0). Also provided is :dunpk which is the inverse function:
#echo off& setlocal enabledelayedexpansion
rem 10/23/2018 daydate.bat: Most recent version at paulhoule.com/daydate
rem Example of date manipulation within a .BAT file.
rem This is accomplished by first packing the date into a single number.
rem This demo .bat displays dates surrounding the current date, prefixed
rem with the day-of-week.
set days=0Mon1Tue2Wed3Thu4Fri5Sat6Sun
call :dgetl y m d
call :dpack p %y% %m% %d%
for /l %%o in (-3,1,3) do (
set /a od=p+%%o
call :dunpk y m d !od!
set /a dow=od%%7
for %%d in (!dow!) do set day=!days:*%%d=!& set day=!day:~,3!
echo !day! !y! !m! !d!
)
exit /b
rem gets local date returning year month day as separate variables
rem in: %1 %2 %3=var names for returned year month day
:dgetl
setlocal& set "z="
for /f "skip=1" %%a in ('wmic os get localdatetime') do set z=!z!%%a
set /a y=%z:~0,4%, m=1%z:~4,2% %%100, d=1%z:~6,2% %%100
endlocal& set /a %1=%y%, %2=%m%, %3=%d%& exit /b
rem packs date (y,m,d) into count of days since 1/1/1 (0..n)
rem in: %1=return var name, %2= y (1..n), %3=m (1..12), %4=d (1..31)
rem out: set %1= days since 1/1/1 (modulo 7 is weekday, Mon= 0)
:dpack
setlocal enabledelayedexpansion
set mtb=xxx 0 31 59 90120151181212243273304334& set /a r=%3*3
set /a t=%2-(12-%3)/10, r=365*(%2-1)+%4+!mtb:~%r%,3!+t/4-(t/100-t/400)-1
endlocal& set %1=%r%& exit /b
rem inverse of date packer
rem in: %1 %2 %3=var names for returned year month day
rem %4= packed date (large decimal number, eg 736989)
:dunpk
setlocal& set /a y=%4+366, y+=y/146097*3+(y%%146097-60)/36524
set /a y+=y/1461*3+(y%%1461-60)/365, d=y%%366+1, y/=366
set e=31 60 91 121 152 182 213 244 274 305 335
set m=1& for %%x in (%e%) do if %d% gtr %%x set /a m+=1, d=%d%-%%x
endlocal& set /a %1=%y%, %2=%m%, %3=%d%& exit /b
If you can change format of short date in the PC to "ddd yyyy-MM-dd" (only first parameter 'ddd' is compulsory), then following command returns-
c:\>vol | date
The current date is: Mon 2014-12-01
Then you can write you batch file -
#echo off
vol | date | find /i "sun" > nul
if not errorlevel 1 goto SUN
vol | date | find /i "mon" > nul
if not errorlevel 1 goto MON
# write block for other week days
goto END
:SUN
set fname="sun"
goto BACKUP
:MON
set fname="mon"
goto BACKUP
# write block for other week days
:BACKUP
echo %fname%
:END
Rem Remove the end comma and add /A to set for this line worked for me.
set /A a=yy/100, b=a/4, c=2-a+b, e=36525*(yy+4716)/100, f=306*(mm+1)/10
Was looking to do this myself and saw complaints about blank lines:
rem Make the win32_localtime output all one line, though some versions may contain blank lines as well.
rem So ignore blank lines and just pick up the number after the equal sign.
for /f "delims== tokens=2" %%a in ('wmic path win32_localtime get dayofweek /format:list') do (
rem Increment the DOW as it is documented to be a zero-based index starting with Sunday.
set /a DayOfWeekIndex=%%a+1
)
rem Also get name day of week. The DOW coming in is now a one-based index.
rem This is used to reference the "array" of week day names.
set DayOfWeekNames=Sun Mon Tue Wed Thu Fri Sat
for /f "tokens=%DayOfWeekIndex%" %%b in ("%DayOfWeekNames%") do (
set DayOfWeekName=%%b
)
I Improved Aacini Answer
to make it Echo Full day of week Name
So here's my Code
#echo off
for /F "skip=1 tokens=2-4 delims=(-/)" %%A in ('date ^< NUL') do (
for /F "tokens=1-3 delims=/" %%a in ("%date%") do (
set %%A=%%a
set %%B=%%b
set %%C=%%c
)
)
set /A mm=10%mm% %% 100, dd=10%dd% %% 100
if %mm% lss 3 set /A mm+=12, yy-=1
set /A a=yy/100, b=a/4, c=4-a+b, e=36525*(yy+4716)/100, f=306*(mm+1)/10,dow=(c+dd+e+f-1523)%%7 + 1
for /F "tokens=%dow%" %%a in ("Sunday Monday Tuesday Wednesday Thursday Friday Saturday ") do set dow=%%a
echo Today is %dow%>"Today is %dow%.txt"
echo Today is %dow%
Pause>Nul
REM Sun Mon Tue Wed Thu Fri Sat
REM Sunday Monday Tuesday Wednesday Thursday Friday Saturday
I use Tiny C to write a weekday.exe and run with batch file.
for /f %% in ('weekday.exe') do set weekday=%%i
weekday.c:
#include <time.h>
#include <stdio.h>
int main(int argc, char** argv) {
time_t curtime;
struct tm * tmval;
time( &curtime );
tmval = localtime( &curtime );
if (tmval->tm_wday == 1) printf("Mon");
if (tmval->tm_wday == 2) printf("Tue");
if (tmval->tm_wday == 3) printf("Wed");
if (tmval->tm_wday == 4) printf("Thu");
if (tmval->tm_wday == 5) printf("Fri");
if (tmval->tm_wday == 6) printf("Sat");
if (tmval->tm_wday == 0) printf("Sun");
return 0;
}
A version using MSHTA and javascript. Change %jsfunc% to whateve jscript function you want to call
#echo off
::Invoke a javascript function using mhta
set jsfunc=new Date().getDay()
set dialog="about:<script>resizeTo(0,0);new ActiveXObject('Scripting.FileSystemObject').
set dialog=%dialog%GetStandardStream(1).WriteLine(%jsfunc%);close();</script>"
for /f "tokens=* delims=" %%p in ('mshta.exe %dialog%') do set ndow=%%p
::get dow string from array of strings
for /f "tokens=%ndow%" %%d in ("Mon Tue Wed Thu Fri Sat Sun") do set dow=%%d
echo dow is : %ndow% %dow%
pause

Resources