PowerShell/Community-Blog

Update request - How can I determine the Day of the Week

doctordns opened this issue · 3 comments

Summary of the update request

To get the day of the week, you use the DateTime's DayOfWeek property, or if you want a numeric result, use value__

KES48 commented

Hi 2 all,

well this is just a try to see what's going on here and how to contribute here in a probably "expected way" :-)

Powershell offers us a cmdlet called get-date which helps to answer most questions around date/time problems.
Try "help get-date -full" if you don't know about that ...

"Get-Date -Date " is used here to first get the DateTime Type representation of your date entered as a string in the simplest form. So we could enter something here to get the required date:

[string]$text=Read-Host -Prompt "Enter a date in the form 'YYYY-MM-DD'"

The next step would be to get the real date out of our string "text" which might fail in many cases.
Dates like february, the 30th are simply not good dates in most parts of the world even if the form '2021-02-30' may be fine :-)
Mostely typos and other maybe even randomly typed strings might not end up to be considered as reasonable dates ....

That said: this kind of type conversion might be very easy to use but might "throw errors"
[datetime]'2021-02-22' works and results in "Montag, 22. Februar 2021 00:00:00"
Even the german form: [datetime]'02.22.2021' works here and gives us the same result.
This one is fine, too: [datetime]'02/22/2021'

But this one e.g.: [datetime]'02222021' makes PS unhappy and throw an error like "can't convert ..... into a valid datetime!

OK, so we have to be aware of wrong input formats as users are always typing the unexpected and making programs abort with errors developers might not have ever seen in their lifes!

If we have got a correct datetime, this type has some wonderful properties like these:

[datetime].GetProperties().Name
Date
Day
**DayOfWeek**
DayOfYear
Hour
Kind
Millisecond
Minute
Month
Now
UtcNow
Second
Ticks
TimeOfDay
Today
Year

So we could use the "DayOfWeek" property and see if we like what happens:

([datetime]'2021-02-22').DayOfWeek
Monday

Easy ... isn't it?

A little console program to do the job might look like this:

[string]$text=Read-Host -Prompt "Enter a date in the form 'YYYY-MM-DD'" 

try {
    [datetime]$date=Get-Date $text
    [string]$dayOfWeek = $date.DayOfWeek 
    "The day of week for [$date] is '$dayOfWeek'"
}
catch {
    "Your data [$text] is not recognized as a valid date"    
}

I hope that this is something that might be expected as an answer to that issue!

Have a nice day
Klaus

Good start

@KES48 Would you be interested in submitting a PR to create this post?