Reputation: 1275
Is it possible to check if the time is in between two ranges and then perform an action based on it.
For eg: I want to perform an action only when the current time is not in between 11.00 PM and 6.00 A.M.
Here's what I have so far but I am unable to pin the in between part.
set "currentTime=!TIME::=!"
set "currentTime=!currentTime:,=!"
set "_bit_compare=leq"
set "compareTime=2300"
set "compareTime1=600"
(time /t | findstr /l "AM PM" || set "_bit_compare=gtr")>nul
if "!currentTime:~0,4=!" %_bit_compare% "!compareTime!" (
do somethinf
)
Upvotes: 1
Views: 2816
Reputation: 16236
This is relatively easy to write using PowerShell. If you are on a supported Windows system, PowerShell will be available. This also overcomes a myriad of problems with regional variations in cmd.exe.
$h = [int](Get-Date -Format "HH")
if ($h -le 8 -or $h -ge 23) { & notepad.exe }"
To use it in a .bat file script, you could:
powershell -NoLogo -NoProfile -Command ^
"$h = [int](Get-Date -Format "HH");" ^
"if ($h -le 8 -or $h -ge 23) { & notepad.exe }"
Upvotes: 0
Reputation: 38589
And just to justify my comment, using wsh, (vbscript), from a batch-file:
<!-- :
@"%__AppDir__%cscript.exe" //NoLogo "%~f0?.wsf"
@If ErrorLevel 1 Exit /B
@Rem Your Commands go below here
@Echo Within range
@Pause
@Rem Your commands end above here
@Exit /B
-->
<Job><Script Language="VBScript">
If Hour(Now())<=22 AND Hour(Now())>=6 Then
WScript.Quit(0 Mod 255)
Else
WScript.Quit(1 Mod 255)
End If
</Script></Job>
I have used Rem
arks to show you where you put your command or commands, and have provided two lines for demonstration purposes, (which you are free to remove once tested).
Upvotes: 2
Reputation: 14290
It is a few lines more to do this in a batch file but you essentially want to get the time in a standard format. You can do that by calling out to WMIC. I am just using the hour to compare. I did not see any need to use minutes based on the provided example saying it is not in between 11.00 PM and 6.00 A.M. I am using a 1 to prefix the comparison incase of leading zeros in the hour.
@echo off
set "compareTime1=23"
set "compareTime2=06"
REM GET DATE and TIME
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
SET "YYYY=%dt:~0,4%"
SET "YY=%dt:~2,2%"
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%"
IF 1%HH% LSS 1%compareTime1% IF 1%HH% GTR 1%compareTime2% (
ECHO LETS DO SOMETHING
)
Upvotes: 1