生日剩余天数计算程序优化:日期格式与异常处理需求
Hey Luca! Let's get your birthday countdown script sorted out with the fixes you need—handling the DD.MM.YYYY format correctly, returning whole days, and catching invalid inputs instead of crashing.
Key Issues Addressed
Your core logic is already there, but we need to tackle three main gaps:
- Ensuring dates are parsed exclusively in
DD.MM.YYYYformat (ignoring system regional settings that might mess this up) - Returning only whole numbers for remaining days (no decimals)
- Adding input validation to catch garbage like "hello" and show a user-friendly error
Full Corrected Code
Clear-Host # Initialize variables $geburtstag = $null $datumvonheute = Get-Date $zeitbisgeburtstag = $null # Get and validate user input do { $inputGeburtstag = Read-Host "Bitte gib deinen Geburtstag im Format DD.MM.YYYY ein" # Force parse input as DD.MM.YYYY, no regional overrides $parseSuccess = [DateTime]::TryParseExact( $inputGeburtstag, "dd.MM.yyyy", [System.Globalization.CultureInfo]::InvariantCulture, [System.Globalization.DateTimeStyles]::None, [ref]$geburtstag ) if (-not $parseSuccess) { Write-Host "⚠️ Ungültiges Datumsformat! Bitte nutze genau das Format DD.MM.YYYY (z.B. 15.08.1990)." -ForegroundColor Red } } while (-not $parseSuccess) # Calculate next occurrence of the birthday $nextBirthday = Get-Date -Year $datumvonheute.Year -Month $geburtstag.Month -Day $geburtstag.Day if ($nextBirthday -lt $datumvonheute) { $nextBirthday = $nextBirthday.AddYears(1) } # Get whole remaining days (no decimals) $remainingDays = [Math]::Floor(($nextBirthday - $datumvonheute).TotalDays) # Output result Write-Host "`nBis zu deinem nächsten Geburtstag sind noch $remainingDays Tage! 🎉" -ForegroundColor Green
What We Changed & Why
Forced Date Format Parsing
Instead of relying on PowerShell's default date parsing (which can vary by region), we useTryParseExactwithdd.MM.yyyyandInvariantCulture—this guarantees only dates in your desired format are accepted.Input Validation Loop
Thedo-whileloop keeps asking for input until a valid date is provided. Invalid entries trigger a clear, red error message instead of crashing the script.Whole Day Calculation
We use[Math]::Floor()on theTotalDaysvalue to strip any decimal points (sinceTotalDaysincludes hours/minutes as fractions). This gives you a clean integer result.Improved User Feedback
Added specific examples in the error message and colored output to make the script more user-friendly.
内容的提问来源于stack exchange,提问作者Luca Miani

