【发布时间】:2019-08-26 08:06:24
【问题描述】:
我在 VB.net 表单上有一个名为 PostDateTxt 的 DatePicker 字段和一个名为 thetime 的 Time 的文本框。我目前正在从表单中读取值,并将它们存储在变量中,其中fullPostDate 以 dd/mm/yyyy 格式保存字符串日期值,postTime 以 hh:mm 格式保存字符串时间值。它们被存储为字符串,因为这是它们在文本框中的格式,我从中获取它们的值。
当我单击表单上的“更新”按钮时,我正在更新数据库中特定项目的日期和时间值。单击“更新”按钮时调用的函数是:
Protected Sub UpdateButton_Click(sender As Object, e As EventArgs) Handles UpdateButton.Click
If Page.IsPostBack Then
...
Dim mypostdate As String = HttpUtility.HtmlEncode(PostDateTxt.Text & " " & theTime.Text)
...
'Split the mypostdate variable into separate String variables for date & time
Dim postDate As DateTime = HttpUtility.HtmlDecode(fullPostDate)
...
...
End Sub
我现在想将这些值转换回 DateTime 对象,并尝试将字符串解析回 DateTime,如下所示:
Dim postDate As DateTime = HttpUtility.HtmlDecode(fullPostDate
但是,当我单步执行我的代码时,当执行上述行时,我会收到一条 Exception User-Unhandled 消息,上面写着:
System.InvalidCastException: '从字符串 "03/29/3019" 到类型 'Date' 的转换无效'
这是为什么?如何将 String 值转换为 Date 对象?
【问题讨论】:
-
DateTime.TryParse?CDate?您可以使用IsDate检查传递的字符串是空白还是非日期 -
冒着头发分裂的风险,您不能将
string转换为DateTime。当一个对象被声明为一种类型但也实现了其他类型(例如通过继承或接口实现)并且您通过这些其他类型之一引用它时,强制转换起作用。 (就像string是object一样,您可以将string转换为object。)string不是DateTime,因此您可以将其转换为一个。您只能解析或转换它,使用string中表示的月、日、年等创建新的DateTime。 -
另外,如果您使用的是 VB.NET,请设置
Option Strict On。默认情况下,VB.NET 将其关闭。这允许像这样的东西编译,然后当它运行时你会得到错误。在运行应用程序之前,最好在编译器中获取错误。您会发现各种不安全的隐式转换正在发生的地方。它会强制你在它运行之前得到所有类型。 -
我之前尝试过
DateTime.Parse,但这似乎不起作用...我刚刚按照您的建议尝试了DateTime.TryParse,使用:If Date.TryParse(fullPostDate, postDate) Then Console.WriteLine(" Converted '{0}' to {1} ({2}).", fullPostDate, postDate, postDate.Kind) End If,但If声明在这里等于 False....