Greet user differently depending on time of day

Issue

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

Solution

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

@echo off
for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set "tim=%%I"
set "tim=%tim:~8,4%"
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 Afternoon %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 "1730" ... works too)

Edited in reaction to your comments.

  • implemented a method to get the time independent of locale settings (in ISO format, which is much better to handle than AM/PM format)
  • Q: "what the extra echo Shouldn't you be in bed %username% after the if statements is for? – A: to handle times between midnight (00:00) and 05:59. Logically it would be if "tim" geq "00" ... but that’s obsolete.
  • Q: "why do you set up the tim variable using set "tim=%time: =0%"? – A: don’t mess with the %time% variable. Setting it disables it’s ability to show the actual time, so we just use another variable name. The set command replaces each space in the string with a zero (obsolete when using wmic to get the time)
  • using a AM/PM in programming is just awkward. Converting a 24h time format to a 12AM/PM format for use in code is pure nonsense (from my (European) background it doesn’t even make sense for "human readability", but ymmv, when you are used to AM/PM)

Answered By – Stephan

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published