0

Caller to a payment line enters 4 digit expiry date MMYY, but I need to make sure this is a valid date in the future.

I have tried get-date but I need to make sure the 4 digit number is converted to a date format before checking against Get-Date Uformat MMyy.

Any Help would be greatfull

Thanks

3 Answers 3

1

Use [DateTime]::ParseExact

$monthYear = "0524"

try {
  if ([DateTime]::ParseExact($monthYear,'MMyy', $null) -gt $(get-date)) {
    Write-Output "valid date in the future" 
  } else {
    Write-Output "valid date in the past"
  }
}
catch {
    Write-Output "invalid date"
}

Change $monthYear to validate the behaviour.

Sign up to request clarification or add additional context in comments.

Comments

0
$read = read-host enter date in the future in format MMYY
try{
    $month = [int]($read[0..1] -join "")
    $year = [int]($read[2..3] -join "")
    $date = get-date -Month $month -Year "20$year"
    if(((get-date) - $date) -le 0){
        write-host "You have entered a valid date in the future: $date" -ForegroundColor Green
    }else{
        Write-Error Not a valid Date 
    }
}catch{
    write-host you have entered an invalid date -ForegroundColor Red
}

Comments

0

Here's my 2-cents using [DateTime]::TryParseExact():

$mmyy = "0524"   # user input

$checkDate = (Get-Date).Date
$thisMonth = (Get-Date -Year $checkDate.Year -Month $checkDate.Month -Day 1).Date
if ([DateTime]::TryParseExact($mmyy, 'MMyy', $null, 'None', [ref]$checkDate)) {
    # [math]::Sign() returns -1 for a negative value, +1 for a positive value or 0 if the value is 0 
    switch ([math]::Sign(($checkDate - $thisMonth).Ticks)) {
        -1 { "$checkDate is in the past" }
         1 { "$checkDate is in the future" }
        default {  "$checkDate is this month" }
    }
}
else {
    write-host "Invalid date" -ForegroundColor Red
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.