我在SQL中有一个Date
列(日期时间数据类型)。对于特定场景,我需要在浏览器中将其显示为空白。我试过了
Dim DOB As Nullable(Of Date) = Date.Now
Dim datestring As String = DOB.Value.ToString("d")
DOB = Nothing
但它给了我错误地说DateTime was not in a proper format
.
这是怎么回事?
你的代码会抛出DateTime was not in a proper format
的原因是因为你很可能不做Dim DOB As Nullable(Of Date) = Date.Now
。您从数据库中获取日期,然后直接输入值,值为空。
假设您有一个带有可为空的日期字段的 Sql 表,并且您使用 DataReader 读取它,您可以这样做
Dim strDate as string
if IsDbNull(reader("myDateColumn")) then
strDate = String.empty
else
DirectCast(reader("myDateColumn"), DateTime).ToString("your format here")
End If
较短的版本将是
Dim strDate as string = If(IsDbNull(reader("myDateColumn")), String.empty,
DirectCast(reader("myDateColumn"), DateTime).ToString("your format here"))
您可以尝试以下任一操作:
Dim datestring As String = IF(DOB Is Nothing,"", DOB.Value.ToString("d"))
或
Dim datestring As String = ""
If Not DoB Is Nothing Then
datestring = DOB.Value.ToString("d")
End If
.HasValue
Null
类型Nullable(Of..)
属性用于签入并.Value
属性来获取使用.ToString
的DateTime
对象
Dim dbdate As Nullable(Of DateTime) = DateTime.Now
Dim datetxt As String = If(dbdate.HasValue = true,
dbdate.Value.ToString("d"),
"")
那么我认为String.Format
会更好使用:
Dim dbdate As Nullable(Of DateTime) = DateTime.Now
Dim datetxt As String = String.Format("{0:d}", dbdate)
dbdate = Nothing
datetxt = String.Format("{0:d}", dbdate)