在 vb.NET 中,字符串未被识别为有效的日期时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32622433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
String was not recognized as a valid DateTime in vb.NET
提问by JTR
I've got this error that said String was not recognized as a valid DateTime, can anyone help me what's wrong here?
我收到了一个错误,提示 String 未被识别为有效的 DateTime,谁能帮我看看这里出了什么问题?
Dim Br As New BL.Bridge
Me.DataSource = Br.List(DateTime.ParseExact(Me.txtTempo.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture)) 'error is right here
Me.ReportPath = "~/report/JaTem.rpt"
Me.HasPrintButton = True
Me.ShowGroupTree = False
If DataSource.Rows.Count > 0 Then
Me.HasPrintButton = True
Server.Transfer("~/report/rpt.aspx")
Else
lblMessage.Text = "No Data!"
End If
if txtTempois filled with date it's work, but when txtTempois empty, it's getting error
如果txtTempo用日期填充它的工作,但是当txtTempo为空时,它会出错
采纳答案by Mark Hall
The DateTime.ParseExactmethod that you are using will give an error when it runs into data that it can't handle. You need to do one of 3 things,
DateTime.ParseExact您使用的方法在遇到无法处理的数据时会出错。你需要做三件事之一,
- validate the data before using the ParseExact method
- use exception handlingto catch the error and notify your user
- or you can use the
DateTime.TryParseExactwhich will give you a Boolean result to indicate if the method succeeded. You would use it something like this.:
- 在使用 ParseExact 方法之前验证数据
- 使用异常处理来捕获错误并通知您的用户
- 或者您可以使用
DateTime.TryParseExact将给您一个布尔结果来指示该方法是否成功。你会像这样使用它。:
Imports System.Globalization
Module Module1
Sub Main()
Dim Date1Data As String = ""
Dim Date2Data As String = "25-09-2015"
Dim result As DateTime
If DateTime.TryParseExact(Date1Data, "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, result) Then
'handle it here
Else
Console.WriteLine("Format Error")
End If
If DateTime.TryParseExact(Date2Data, "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, result) Then
Console.WriteLine(result) 'handle it here
Else
Console.WriteLine("Format Error")
End If
Console.ReadLine()
End Sub
End Module
or modifying your code something like this should work.
或修改您的代码这样的东西应该可以工作。
Dim Br As New BL.Bridge
Dim result as Date
If DateTime.TryParseExact(Me.txtJatem.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, result) Then
Me.DataSource = Br.List(result) 'error is right here
Me.ReportPath = "~/report/JaTem.rpt"
Me.HasPrintButton = True
Me.ShowGroupTree = False
If DataSource.Rows.Count > 0 Then
Me.HasPrintButton = True
Server.Transfer("~/report/rpt.aspx")
Else
lblMessage.Text = "No Data!"
End If
Else
lblMessage.Text = "Format Error, please check input and try again"
End If

