Converting User Input to Date

by Dec 31, 2008

PowerShell uses the US/English date format when converting user input to DateTime, which can cause unexpected results if using a different culture. For example, on German systems "1.3.2000" resolves to March 1, 2000. PowerShell can convert this input to January 3, 2000.

To convert DateTime values based on your current culture, use the DateTime's parse() method:

[DateTime]::Parse('1.3.2000')

But what if the user enters nonsense that cannot be converted to a date? You get an exception!

There are two workarounds. First, you can start using -as to see if the user input can be converted to a DateTime at all. If so, use parse() to get the culture-specific date:

$date = Read-Host 'Enter your birthday'
if (($date -as [DateTime]) -ne $null) {
$date = [DateTime]::Parse($date)
$date
} else {
'You did not enter a valid date!'
}

Secondly, you can use an error handler to catch the exception like so:

$date = Read-Host 'Enter your birthday'
trap {'You did not enter a valid date!'continue}
. {
$date = [DateTime]::Parse($date)
$date
}