【问题标题】:cType : string to date throwing InvalidCastException (ASP) (VB.NET)cType : string to date throwing InvalidCastException (ASP) (VB.NET)
【发布时间】:2014-07-15 05:14:54
【问题描述】:

我在以下几行中遇到异常

InspectionDate = "07/15/2014"
If CType(InspectionDate, Date) > Date.Today Then

    'Here comes my logic etc
    'Here comes my logic etc
    'Here comes my logic etc

 End If

当我调试时,我看到 Date.Today = #7/15/2014#

谁能帮忙解决一下。

谢谢..

【问题讨论】:

  • 改用datetime.parse
  • 我只需要比较日期而不是时间。你也可以请给我的示例代码。对不起,我是asp.net的初学者

标签: asp.net vb.net visual-studio-2005


【解决方案1】:

这样试试

Dim dt As Date = Date.ParseExact("07/15/2014","MM/dd/yyyy", CultureInfo.InvariantCulture); 
IF dt > Date.Today Then
    'CODE HERE
END IF

msdn查看完整文档

【讨论】:

  • 我在 ParseExact、CultureInfo 和 InvariantCulture 上收到“未声明的元素”
  • 谢谢,我必须导入 system.globalization
  • 哦.. 抱歉,我的回答中没有提到这一点。
【解决方案2】:
InspectionDate = "07/15/2014"
If DateTime.Parse(InspectionDate) > Date.Today Then

    'Here comes my logic etc
    'Here comes my logic etc
    'Here comes my logic etc

 End If

这样试试

【讨论】:

  • 现在我得到了:System.FormatException: String was not recognized as a valid DateTime. at ...
  • @Anjum 那是因为给定的日期格式和您当前的文化日期格式不同,否则它应该可以完美地工作。
  • 感谢您的解释:)
【解决方案3】:

在比较两个日期之前使用 TryParse 方法

 Dim dateValue as Date
 InspectionDate = "07/15/2014"
 If (Date.TryParse(InspectionDate, dateValue) > Date.Today Then

      'your code here

 End If

查看 MSDN 中的方法 check the description

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-18
    • 1970-01-01
    • 2020-07-27
    • 2015-11-06
    • 2016-05-27
    • 2020-03-27
    • 2015-12-19
    • 1970-01-01
    相关资源
    最近更新 更多