You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

生日剩余天数计算程序优化:日期格式与异常处理需求

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.

Fixed Birthday Countdown Script (PowerShell)

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.YYYY format (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

  1. Forced Date Format Parsing
    Instead of relying on PowerShell's default date parsing (which can vary by region), we use TryParseExact with dd.MM.yyyy and InvariantCulture—this guarantees only dates in your desired format are accepted.

  2. Input Validation Loop
    The do-while loop keeps asking for input until a valid date is provided. Invalid entries trigger a clear, red error message instead of crashing the script.

  3. Whole Day Calculation
    We use [Math]::Floor() on the TotalDays value to strip any decimal points (since TotalDays includes hours/minutes as fractions). This gives you a clean integer result.

  4. Improved User Feedback
    Added specific examples in the error message and colored output to make the script more user-friendly.

内容的提问来源于stack exchange,提问作者Luca Miani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:34:12