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

VB.Net日期解析异常求助:无法识别有效DateTime

Fixing the System.FormatException in Your VB.Net Date Comparison

Let's break down why you're hitting that System.FormatException and how to fix it quickly:

The Root Problem

Your code is doing unnecessary conversions between DateTime and strings, which introduces format mismatch risks. Here's the problematic line:

ElseIf Date.Parse(expirationDTP.Value.ToString("MM/dd/yyyy")) <= Date.Parse(Date.Now.ToString("MM/dd/yyyy")) Then
  • expirationDTP.Value is already a DateTime object—no need to convert it to a string and parse it back.
  • Date.Now is also a DateTime object for the same reason.
  • When you use Date.Parse without specifying a format provider, it relies on the system's regional settings. If your system's default date format isn't MM/dd/yyyy, parsing that string will fail with the exact error you're seeing.

The Simple Fix

Skip all the string conversion and compare the DateTime objects directly:

ElseIf expirationDTP.Value.Date <= Date.Now.Date Then
    MsgBox("Select the expiration date of the stock!")

Adding .Date ensures you're comparing just the date part (ignoring time), which matches what you were trying to do by formatting to MM/dd/yyyy.

Extra Tips to Avoid This in the Future

  • Never convert DateTime to strings for comparison: It's inefficient and error-prone due to regional settings.
  • If you ever need to parse strings to DateTime explicitly, use Date.ParseExact or Date.TryParseExact with a specific format and culture provider to avoid ambiguity:
    Dim inputDate As String = "10/25/2024"
    Dim parsedDate As DateTime
    If Date.TryParseExact(inputDate, "MM/dd/yyyy", Globalization.CultureInfo.InvariantCulture, Globalization.DateTimeStyles.None, parsedDate) Then
        ' Use parsedDate here
    Else
        MsgBox("Invalid date format!")
    End If
    

内容的提问来源于stack exchange,提问作者Brian Nebres

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:42:07