Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check that a string contains a date?

Tags:

powershell

My script's input parameter is a date or a number. Here's a script that works fine, so you can see what I am trying to do:

param($date = (Get-Date))

if ($date -match "^\d+$")
{  
    $date = (Get-Date).AddDays($date)
} 
elseif ($date -as [DateTime]) 
{
    $date = [DateTime]::Parse($date)  
}
else 
{  
    'You entered an invalid date'
    exit 1
}

Here's my previous attempt that does not work:

param($date = (Get-Date))

if ($date -as [DateTime]) 
{
    $date = [DateTime]::Parse($date)  
}
elseif ($date -match "^\d+$")
{  
    $date = (Get-Date).AddDays($date)
} 
else 
{  
    'You entered an invalid date'
    exit 1
}

When I input a number, the script breaks at date parsing line. It looks like my "is is date" check returns true when given a number.

Is it a bug? Is it by design?

like image 613
buti-oxa Avatar asked Jan 06 '10 17:01

buti-oxa


People also ask

How do you check if a string contains date or not?

TryParseExact("15:30:20", "yyyy-MM-dd HH:mm:ss",CultureInfo.

How do you check if a string is a date Java?

There are two possible solutions: Use a SimpleDateFormat and try to convert the String to Date . If no ParseException is thrown the format is correct. Use a regular expression to parse the String.

How check string is date or not in C#?

TryParse() function to check if a particular string is a valid datetime not depending on any cultures. To my surprise , the function returns true for even strings like "1-1", "1/1" . etc.


1 Answers

This is a short alternative:

function isDate([string]$strdate)
{
    [boolean]($strdate -as [DateTime])
}
like image 105
JD2MCSE Avatar answered Oct 04 '22 21:10

JD2MCSE