How I can check the date using a calender , what I want to do is that a user insert a date in this way 2012/07/15 , and i want to check if this date exist in the calender .
for example if he insert 2012/14/13 or even 2012/02/31 , i tried to do that manually but its really hard , so my qustions are :
is there a native function(or even 3d party tools) to check date in calender ?
if the user insert date and hour , I want to give same result with different time zone places ?
There is no simple native batch command that will validate your string.
Here is a batch subroutine that can be used to validate the date string.
#echo off
setlocal
set "dt="
set /p "dt=Enter a date in yyyy/mm/dd format: "
if not defined dt exit /b
call :validateDate dt && (echo date is valid) || (echo ERROR: date is invalid)
exit /b
:validateDate
setlocal enableDelayedExpansion
echo !%~1!|findstr /rx "[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9]" >nul || exit /b 1
for /f "tokens=1,2,3 delims=/" %%A in ("!%~1!") do (
set /a "yyyy=10000%%A%%10000, mm=100%%B%%100, dd=100%%C%%100" || exit /b 1
)
if %mm% lss 1 exit /b 1
if %mm% gtr 12 exit /b 1
if %dd% lss 1 exit /b 1
set "months=;1-31;2-28;3-31;4-30;5-31;6-30;7-31;8-31;9-30;10-31;11-30;12-31;"
for /f "delims=;" %%A in ("!months:*;%mm%-=!") do set maxDays=%%A
set /a "divBy4=yyyy%%4, divBy100=yyyy%%100, divBy400=yyyy%%400"
if %mm% equ 2 if %divBy4% equ 0 (
if %divBy100% neq 0 set /a maxDays+=1
if %divBy400% equ 0 set /a maxDays+=1
)
if %dd% gtr %maxDays% exit /b 1
exit /b 0
It will only accept 4 digit years, 2 digit months, and 2 digit days as you have posted in your question. If you want to support 1 digit months or days, then change the FINDSTR to the following:
echo !%~1!|findstr /rx /c:"[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9]" ^
/c:"[0-9][0-9][0-9][0-9]/[0-9]/[0-9][0-9]" ^
/c:"[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9]" ^
/c:"[0-9][0-9][0-9][0-9]/[0-9]/[0-9]">nul || exit /b 1
I don't understand what you want to do with the date and time zones.
The subroutine below is comprised of two parts. First it check the date given in 1st parameter and return ERRORLEVEL=1 if the date is bad. You may insert a year valid range if you wish (otherwise, remove the yyOK parts).
Then it takes a base hour and time-zone adjust in 2nd and 3rd parameters and show the adjusted date.
:validateDate result= YYYY/MM/DD [HH HHAdjust]
setlocal EnableDelayedExpansion
set i=0
for %%a in (31 28 31 30 31 30 31 31 30 31 30 31) do (
set /A i+=1
set daysPerMonth[!i!]=%%a
)
set result=Invalid date
for /F "tokens=1-3 delims=/" %%a in ("%2") do set yy=%%a& set mm=%%b& set dd=%%c
set /A yy=%yy%, mm=10%mm% %% 100, dd=10%dd% %% 100, yyMOD4=yy%%4 >NUL 2>&1 || goto exit
if %yyMOD4% equ 0 set daysPerMonth[2]=29
set /A yyOK=0, mmOK=0, ddOK=0
rem Modify year limits as you wish (or remove they):
if %yy% geq 1900 if %yy% leq 2015 set yyOK=1
if %mm% geq 1 if %mm% leq 12 set mmOK=1
id %dd% geq 1 if %dd% leq !daysPerMonth[%mm%]! set ddOK=1
set /A dateOK=yyOK*mmOK*ddOK
if %dateOK% neq 1 goto exit
rem Date is correct
set result=%yy%/%mm%/%dd%
rem Adjust the hour to different time zone, if given
rem %3=base hour, %4=adjust with sign (+ or -)
if "%4" equ "" goto exit
set /A newHH=10%3 %% 100 %4
if %newHH% gtr 23 (
rem Pass to next day
set /A newHH-=24, dd+=1
if !dd! gtr !daysPerMonth[%mm%]! (
set /A dd=1, mm+=1
if !mm! gtr 12 (
set /A mm=1, yy+=1
)
)
)
if %newHH% lss 1 (
rem Pass to previous day
set /A newHH+=24, dd-=1
if !dd! lss 1 (
set /A mm-=1
if !mm! lss 1 (
set /A mm=12, yy-=1
)
for %%m in (!mm!) do (
set /A dd=daysPerMonth[%%m]
)
)
)
set result=%yy%/%mm%/%dd% %newHH%
:exit
endlocal & set %1=%result%
exit /B
Test this program and report any problem.
EDIT: I have modified previous program to fit new OP's requirements.
The subroutine no longer returns an ERRORLEVEL value with the result. It must be called now with a new first parameter that indicate the variable that will receive the result, that will be "Invalid date" if original date is bad. If a base and adjustment hours are given, returned value include the adjusted date and hour. For example:
call validate.bat adjusted= 2012/3/5 3 -2
if "%adjusted%" neq "Invalid date" (
echo Adjusted date and hour are: %adjusted%
)
Antonio
Related
This question already has an answer here:
How to generate succesive dates? (add N days to date)
(1 answer)
Closed last month.
I have bat script for loop function
#echo off set /p a="Start Date(yyyymmdd):"%=% set /p b="Finish Date
(yyyymmdd):"%=%
echo %a% echo %b%
echo start loop
FOR /L %%c IN (%a%,1,%b%) DO ( echo %%c
set inputan=%%c
call test_loopong.bat %inputan%
)
I need to run according to the range of start and end date input.
But from the script above, for example the start date is 20221231 and the end date is 20230103
will loop all numbers from 20221231, 20221232, 20221233......20230103
Please someone can help me.
Thanks
#ECHO Off
SETLOCAL
set /p "startdate=Start Date(yyyymmdd):"
set /p "finishdate=Finish Date (yyyymmdd):"
echo %startdate%
echo %finishdate%
IF %finishdate% lss %startdate% ECHO Invalid DATE range&GOTO :eof
echo start loop
FOR /L %%c IN (%startdate%,1,%finishdate%) DO (
FOR /F %%y IN ('set /a inputan^=%%c %% 100') DO IF %%y lss 32 IF %%y gtr 0 (
echo %%c
set /a inputan=%%c
call :test_loopong.bat %%c
)
)
GOTO :EOF
:test_loopong.bat
ECHO IN test_loopong : %%1=%1 inputan=%inputan%
GOTO :eof
I changed the variable names so that they are maintainable, 'though I've no idea what inputan means.
Added invalid date-range check.
Note syntax of set /p
Forget for the moment what for...%%y... does.
I used a set /a since %%c must be numeric.
Use set "var1=value" for setting STRING values - this avoids problems caused by trailing spaces.
I converted test_loopong.bat to an internal subroutine (call :name) for demonstration purposes to avoid having to generate another file.
I'm having that subroutine simply display the value of the variable inputan and the parameter %1. %%c can be delivered as a parameter to the subroutine (be it internal or external) but your syntax would appear to omit the parameter because of the delayed expansion trap - %var% will be replaced by the value of var at the time the outer loop (for...%%c) is encountered.
Now the for...%%y jiggery-pokery.
The command set /a inputan=%%c % 100 would set inputan to %%c mod 100. There's no importance about the variable name - that one's about to be assigned a different value again in a couple of lines.
When used in a for /f, batch will execute the set/a command and echo the result to the metavariable %%y.
However, = and % are special characters and need to be "escaped" (interpreted without their special meaning). Th escape character for most specials is caret (^) but for % is % itself.
The result of the calculation is assigned to %%y and we can then test that %%y is lss 32 - Less than 32, and also it is gtr 0 - Greater than 0. Only then do we call test_loopong.bat. This eliminates most non-dates
If you don't want to skip the non-dates, then remove the for...%%y line and delete one of the ) lines.
--- further thoughts ----
Suppressing the days 32..99 & 00 really only does half the job. Much better if we suppress months 13..99 & 00. The revision then would be (presenting just the main loop, minus the frippery)
FOR /L %%c IN (%startdate%,1,%finishdate%) DO (
FOR /F %%e IN ('set /a inputan^=%%c %% 10000') DO IF %%e lss 1232 IF %%e gtr 100 (
FOR /F %%y IN ('set /a inputan^=%%c %% 100') DO IF %%y lss 32 IF %%y gtr 0 (
echo %%c
set /a inputan=%%c
call :test_loopong.bat %%c
)
)
)
Same principle, just dealing with months in place of days.
One slight problem with this method is that it's as slow as a wet week.
So - a different approach
SET /a yyyy=%startdate:~0,4%
SET /a mm1=1%startdate:~4,2%
SET /a dd1=1%startdate:~-2%
:loop2
SET /a inputan=%yyyy%0000+%mm1%00+dd1-10100
IF %inputan% gtr %finishdate% GOTO :eof
CALL :test_loopong.bat %inputan%
SET /a dd1+=1
IF %dd1% leq 131 GOTO loop2
SET /a dd1=101&SET /a mm1+=1
IF %mm1% leq 112 GOTO loop2
SET /a mm1=101
SET /a yyyy+=1
GOTO loop2
This sets yyyy to the year and mm1/dd1 to 100+(month/day). 100+ needs to be done since batch regards a numeric string that starts 0 as
octal hence August and September cause problems.
So - calculate inputan by tringing 4 0s to yyyy, adding 100*mm1 and dd1, then subtracting 10100 since mm1 is mm+100 and dd1 is dd+100.
If the resultant inputan is greater than the finish date, end the routine.
Test using inputan.
Next day - add 1 to dd1.
If the result is less than or equal to 131, we're fine.
Otherwise set dd1 to 101 and increment the month
Same recipe for mm1, limit is 112 and bump the year if required.
---- Further revision to deal with non-dates 31st Apr, Jun, Sep, Nov and Feb (include leap years) ---
#ECHO Off
SETLOCAL
set /p "startdate=Start Date(yyyymmdd):"
set /p "finishdate=Finish Date (yyyymmdd):"
echo %startdate%
echo %finishdate%
IF %finishdate% lss %startdate% ECHO Invalid DATE range&GOTO :eof
echo start loop
GOTO ver2
FOR /L %%c IN (%startdate%,1,%finishdate%) DO (
FOR /F %%e IN ('set /a inputan^=%%c %% 10000') DO IF %%e lss 1232 IF %%e gtr 100 (
FOR /F %%y IN ('set /a inputan^=%%c %% 100') DO IF %%y lss 32 IF %%y gtr 0 (
echo %%c
set /a inputan=%%c
call :test_loopong.bat %%c
)
)
)
GOTO :EOF
:ver2
SET /a yyyy=%startdate:~0,4%
SET /a mm1=1%startdate:~4,2%
SET /a dd1=1%startdate:~-2%
:loop2
SET /a inputan=%yyyy%0000+%mm1%00+dd1-10100
IF %inputan% gtr %finishdate% GOTO :eof
CALL :test_loopong.bat %inputan%
SET /a dd1+=1
SET /a inputan=yyyy %% 4
IF %mm1%==102 IF %dd1% gtr 129 (GOTO nextmonth) ELSE IF %inputan% neq 0 IF %dd1%==129 GOTO nextmonth
FOR %%e IN (104 106 109 111) DO IF %%e131==%mm1%%dd1% GOTO nextmonth
IF %dd1% leq 131 GOTO loop2
:nextmonth
SET /a dd1=101&SET /a mm1+=1
IF %mm1% leq 112 GOTO loop2
SET /a mm1=101
SET /a yyyy+=1
GOTO loop2
GOTO :eof
:test_loopong.bat
ECHO IN test_loopong : %%1=%1 inputan=%inputan%
GOTO :eof
I want to make a batch script that counts how long it's been run in seconds. How can I do this?
Hope you would like it. >u<
Add this into the first line of the batch that you wanted to count its running time:
echo %time% >"starting time.any-file-type"
And that into the end(s) of the batch file:
(start) "counter.bat"
Code of "counter.bat"
#echo off
set thetimenow=%time%
set /p thetimebefore=<"starting time.any-file-type"
set /a hours=%thetimenow:~0,2% - %thetimebefore:~0,2%
set /a mins=%thetimenow:~3,2% - %thetimebefore:~3,2%
set /a seconds=%thetimenow:~6,2% - %thetimebefore:~6,2%
set /a minsecs=%thetimenow:~9,2% - %thetimebefore:~9,2%
if %minsecs% lss 0 (set /a seconds-=1
set /a minsecs+=100)
if %seconds% lss 0 (set /a mins-=1
set /a seconds+=60)
if %mins% lss 0 (set /a hours-=1
set /a mins+=60)
if %hours% lss 0 (set /a days=1
set /a hours+=24)
if not "%days%" == "1" (set days=) else (set days=1 or more days, )
echo The batch required has ran for %days%%hours% hour(s), %mins% minute(s), %seconds% second(s), and %minsecs% miniseconds.
That's the best that I can give.
Note that the required batch must NOT contain the keyword exit.
If needed, use chcp 437 right before the line which contains %time%.
Make sure the batches are at the same folder if you don't wish to modifiy the code which calls for the counter.
...
rem Change formatting for the start and end times
for /F "tokens=1-4 delims=:.," %%a in ("%function_starttime%") do (
set /A "start=(((%%a*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100"
)
for /F "tokens=1-4 delims=:.," %%a in ("%function_endtime%") do (
set /A "end=(((%%a*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100"
)
REM To avoid rollover errors, add 24 hours (in hundredths of a
REM second) if the end time is past midnight
REM 24 hours * 60 minutes * 60 seconds * 100 = 8,640,000 hundredths of
REM a second
if %end% lss %start% set /A end=end+(24*60*60*100)
rem Calculate the elapsed time by subtracting values
set /A elapsed=end-start
...
I'm new to batch scripting and don't understand why double digit numbers evaluate as less than single digit?
%weekdayOffPeakEnd% variable is 7 when echo'd.
I'm calling this sleepUntilOffPeak function from within a FOR loop (not shown) but I don't think that has any impact because I don't use any variables from this function anywhere else in the script. This function simply checks the current hour and "sleeps" until electricity rates are low again.
Thx
rem if not currently off-peak hours, wait (timeout) until electricity rates are lowest
:sleepUtilOffPeak
rem set DayofWeek and Hour variables
for /f %%a in ('wmic path win32_localtime get DayOfWeek /format:list ^| findstr "="') do (set %%a)
for /f %%a in ('wmic path win32_localtime get Hour /format:list ^| findstr "="') do (set %%a)
rem echo Day of week^: %DayOfWeek%
echo Hour^: %Hour%
rem set OffPeak variables
set /a weekdayOffPeakEnd=07
echo weekdayOffPeakEnd^: %weekdayOffPeakEnd%
set /a weekdayOffPeakStart=23
set /a weekendOffPeakEnd=15
set /a weekendOffPeakStart=19
set weekday=true
if "%DayOfWeek%" EQU "0" set weekday=false
if "%DayOfWeek%" EQU "6" set weekday=false
rem echo weekday^: %weekday%
if %weekday% equ true (
echo Today is a weekday
if Hour LSS weekdayOffPeakEnd (
echo %Hour% is less than off-peak end^: %weekdayOffPeakEnd%. Returning...
exit /B 0
) else (
if Hour GEQ weekdayOffPeakStart (
echo %Hour% is greater than or equal to off-peak start^: %weekdayOffPeakStart%. Returning...
exit /B 0
) else ( rem Hour is between 07 and 23
rem sleep until offPeak then return
set /a sleepTime=23-%Hour%
set /a sleepSeconds=%sleepTime%*3600
echo Going to sleep for %sleepSeconds% seconds
timeout /t %sleepSeconds%
exit /B 0
)
)
) else ( rem weekday equ false
echo Today is a weekend
if Hour LSS weekendOffPeakEnd (
echo %Hour% is less than off-peak end^: %weekendOffPeakEnd%. Returning...
exit /B 0
) else (
if Hour GEQ weekendOffPeakStart (
echo %Hour% is greater than or equal to off-peak start^: %weekendOffPeakStart%. Returning...
exit /B 0
) else ( rem Hour is between 15 and 19
rem sleep until offPeak then return
set /a sleepHours=%weekendOffPeakStart%-%Hour%
echo sleepHours^: %sleepHours%
set /a sleepSeconds=%sleepHours%*3600
echo Going to sleep for %sleepSeconds% seconds
timeout /t %sleepSeconds%
echo All done sleeping. Returning...
exit /B 0
)
)
)
You have many examples like this:
if Hour LSS weekdayOffPeakEnd (
This compares the literal Hour to the literal weekdayOffPeakEnd
You need
if %Hour% LSS %weekdayOffPeakEnd% (
Further, if you change the value of any variable within a code block (parenthesised code) then you need to retrieve the changed value using !var! having invoked delayed expansion (use search to locate many SO items)
Also, you observe that set /a var=07 will set the variable to 7, not 07. It's important to understand the difference between set /a and set. set /a resolves the value to be assigned and then assigns that value as a string to the variable, suppressing leading zeroes. set assigns the literal including leading zeroes.
This leads to two consequences. First, a value that starts with 0 is assigned by set/a as an OCTAL value, so 08 and 09 will be invalid. And second, if %var% op val will attempt to convert both arguments of the operator to numeric to perform the comparison, and if both conversions are successful, then the comparison is executed as a numeric comparison, otherwise it's executed as a string comparison where the characters are matched serially from the left.
i have writing a window batch to del the files order than 3 months in some directory, however, there are some problem on :Loop_Folder_Del_Old_Files. I don't know why i cannot assign the last modified date of the files, please help to find out the problem. Below are the source code and program result, thanks!
Source Code
:program_start
#ECHO ON
echo program_start
:Parameter_Settings
set filePath=c:\New Folder
set delPeriod=3
echo %date%
set curYYYY=%date:~10,4%
set curMM=%date:~7,2%
set curDD=%date:~4,2%
:Set_The_Date_Of_3_Months_Ago
set /A curMM=curMM - %delPeriod%
if "%curMM%" LEQ "0" (
set /A curMM="(curMM + 12 - %delPeriod%)%%12"
if %curMM% == 0 (set curMM=12) ELSE (set curMM=%curMM%)
set /A curYYYY=curYYYY - 1
)
set curMM=00%curMM%
set curMM=%curMM:~-2%
set curDate=%curYYYY%%curMM%%curDD%
:Loop_Folder_Del_Old_Files
for %%a IN ("%filePath%\*.*") DO (
set ltdate=%%~ta
set fileDate=%ltdate:~6,4%%ltdate:~3,2%%ltdate:~0,2%
if "%fileDate%" LSS "%curDate%" Del /Q "%%a"
)
:end
echo program end
pause
Result
C:\>echo program_start
program_start
C:\>set filePath=c:\New Folder
C:\>set delPeriod=3
C:\>echo Fri 22/11/2013
Fri 22/11/2013
C:\>set curYYYY=2013
C:\>set curMM=11
C:\>set curDD=22
C:\>set /A curMM=curMM - 3
C:\>if "8" LEQ "0" (
set /A curMM="(curMM + 12 - 3)%12"
if 8 == 0 (set curMM=12 ) ELSE (set curMM=8 )
set /A curYYYY=curYYYY - 1
)
C:\>set curMM=008
C:\>set curMM=08
C:\>set curDate=20130822
C:\>for %a IN ("c:\New Folder*.*") DO (
set ltdate=%~ta
set fileDate=~6,4%ltdate:~3,2%ltdate:~0,2
if "" LSS "20130822" Del /Q "%a"
)
C:\>(
set ltdate=22/11/2013 05:36 PM
set fileDate=~6,4%ltdate:~3,2%ltdate:~0,2
if "" LSS "20130822" Del /Q "c:\New Folder\New Text Document (2).txt"
)
C:\>(
set ltdate=22/11/2013 05:36 PM
set fileDate=~6,4%ltdate:~3,2%ltdate:~0,2
if "" LSS "20130822" Del /Q "c:\New Folder\New Text Document.txt"
)
C:\>echo program end
program end
C:\>pause
Press any key to continue . . .
maybe the use of forfiles to delete old files could be better in handle?
You need to enable delayed expansion to make your variables work inside the for loop.
Add
setlocal enabledelayedexpansion
at the top of your bat file
and then, refer to the variable using the !var! syntax (instead of %var%)
if "!fileDate!" LSS "!curDate!" Del /Q "%%a"
Further to PA's correct response,
set /A curMM=curMM - %delPeriod%
if "%curMM%" LEQ "0" (
set /A curMM="(curMM + 12 - %delPeriod%)%%12"
if %curMM% == 0 (set curMM=12) ELSE (set curMM=%curMM%)
set /A curYYYY=curYYYY - 1
)
Is unreliable as currMM may be 08 or 09 which would generate a syntax-error as batch assumes that any numeric starting with 0 is OCTAL.
set /A curMM=1%curMM% - 100 - %delPeriod%
if %curMM% LEQ 0 (
set /A curMM=curMM + 12
set /A curYYYY=curYYYY - 1
)
is better. The comparison is executed against the NUMERIC value, not a string value. The value of curMM would be 0 for Dec, -1 for Nov, etc - so simply adding 12 and subtracting 1 from the year is sufficient and clearer.
:Life
set /a R=%random%%%50+1
echo %random% >> %R%.bat
set /a t=%time:~6,-3%
If %t% geq 10 (
set /a t=%t%-10
) else (
set /a t=%t%+10
)
:wait
If %time:~6,-3% neq %t% goto :Wait
:death
set /a K=%random%%%50+1
del /Q %K%.bat
:disease
set /a D=%random%%%150+1
If %D% EQU 150 del /Q *.bat (
goto Life
) else (
If %D% EQU 150 echo On Error Resume Next > temp.vbs
If %D% EQU 150 echo MsgBox "Disease Killed The Biome", vbInformation + vbSystemModal + vbOKOnly, "Life.exe" >> temp.vbs
If %D% EQU 150 cscript temp.vbs
If %D% EQU 150 del temp.vbs
goto Life
)
:EOF
So my issue is the timer engine. The counter itself contains 00–59 but the other is 0–59 so when the ticker hits a number and it has a value of 9 or less it'll skip them on the next passover because they don't have 09 (etc.), is there a way where I can set the code to other ticker to stay at 59 the whole time?
It would be easier to read, if you could format your code a little bit.
To solve your current problem, you could use the time to decimal trick.
set /a t=1%time:~6,-3%-100
Else you got problems with the times 08 and 09, because of the leading zero, it assumes it should be an octal value and fails.
And in the wait-loop you could use the same way
:wait
set /a now=1%time:~6,-3%-100
If %now% neq %t% goto :Wait
But to wait a time it is better to use the way,
ping localhost -n [sec]+1 > NUL
because the your way consumes the 100% cpu (one core).