Home > Mobile >  Greet user differently depending on time of day
Greet user differently depending on time of day

Time:11-23

I have the following Windows Batch File that I have found to greet the user with Good Morning or Good Evening depending on the time of day:

for /f "delims=:" %%A in ("%time%") do if %%A LSS 12 (echo. Good Morning %username%.) else (echo. Good Afternoon %username%.)

However, I would like it to respond based on the following rules:

If the time is 06:00 to 11:59 the greeting should be "Good Morning %username%"

If the time is 12:00 to 17:59 the greeting should be "Good Afternoon %username%"

If the time is 18:00 to 19:59 the greeting should be "Good Evening %username%"

If the time is 20:00 to 05:59 the greeting should be "Shouldn't you be in bed %username%?"

Could some one please advise if this is possible and if so let me know how?

Many thanks,

Bri

CodePudding user response:

No need to employ a for loop to dissect %time%. Just take advantage of how string comparisons are done:

@echo off
set "tim=%time: =0%"
if "%tim%" geq "20" echo Shouldn't you be in bed %username%?&goto :done
if "%tim%" geq "18" echo Good Evening %username%&goto :done
if "%tim%" geq "12" echo Good Morning %username%&goto :done
if "%tim%" geq "06" echo Good Morning %username%&goto :done
echo Shouldn't you be in bed %username%
:done

(just to note: if "%time%" geq "17:30" ... works too)

CodePudding user response:

For clarity, below is the fully working solution I used.

NOTE: I am converting the time to a 12 hour format and adding AM/PM.

@echo off &cls
setlocal

REM Get system time and convert to 12 hour format
for /F "tokens=1,2,3 delims=:,. " %%A in ('echo %time%') do (
set /a "hour=100%%A%0"
set min=%%B
set sec=%%C
)

REM Add AM/PM
if %hour% geq 12 (
set ampm=PM
set /a "hour-=12"
) else set "ampm=AM"
if %hour% equ 0 set "hour=12"
if %hour% lss 10 set "hour=0%hour%"

REM Set up custom variables: - %hour% %min% %sec% %ampm%
set time=%hour%:%min%%ampm%


REM Greet user differently depending on the time
if "%time%" geq "10:00pm" echo. It's %time%^! Bit late to be working isn't it %username%? &goto :done
if "%time%" geq "06:00pm" echo. Good Evening %username%, the time is %time%. &goto :done
if "%time%" geq "12:00pm" echo. Good Afternoon %username%, the time is %time%. &goto :done
if "%time%" geq "06:00am" echo. Good Morning %username%, the time is %time%. &goto :done
echo. It's %time%^! Bit late to be working isn't it %username%?
:done

endlocal
echo. &echo. Press any key to exit &>nul timeout /t -1 &exit /B
  • Related