使用 isDate 返回 true vb.net

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30612272/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 19:10:53  来源:igfitidea点击:

Using isDate return true vb.net

vb.net

提问by Gimo Gilmore

When I'm using isDate()Method in .NET. It returns invalid result. Why "AD05AD09" is read as date. following is the code i'm using. Please give me proper reason for this

当我isDate()在 .NET 中使用Method 时。它返回无效的结果。为什么将“AD05AD09”读作日期。以下是我正在使用的代码。请给我适当的理由

    Dim value As String
    value = "AD05AD09"
    If IsDate(value) Then
        Dim oDate As Date
        oDate = CDate(value)
        MsgBox(Format(oDate, "yyyy-MM-dd"))
    Else
        MsgBox("a")
    End If

回答by loadingnow

It is counted as a date because the first "AD" like said in http://en.wikipedia.org/wiki/Anno_Domini, AD is placed before the year, but because the 05 is not 4 digit but 2 digit, the functions treat it as the month. The second AD counts as a valid delimiter in the date like in "12AD12AD2008" is 12/12/2008.

它被算作日期,因为第一个“AD”就像http://en.wikipedia.org/wiki/Anno_Domini 中所说的那样,AD 放在年份之前,但是因为 05 不是 4 位而是 2 位,所以函数把它当作月份。第二个 AD 算作日期中的有效分隔符,例如“12AD12AD2008”是 12/12/2008。

So,

所以,

CDate("AD05AD09") '= 05/09
CDate("10AD10AD2000") '=10/10/2000

and so on.

等等。

But BC doesn't work, because BC can't be stored in a date, since you can't store negative years...

但是 BC 不起作用,因为 BC 不能存储在日期中,因为您不能存储负年份...

回答by ilans

As writtern in MSDN:

正如MSDN 中所写:

IsDate returns True if Expression is of the Date Data Type or can be converted to Date; otherwise, it returns False.

如果表达式是日期数据类型或可以转换为日期,则 IsDate 返回 True;否则,它返回 False。

But you should go for the common ways, which are DateTime.Parse, DateTime.ParseExact, Convert.ToDateTimeand more.

但是你应该去为常见的方式,这是DateTime.ParseDateTime.ParseExactConvert.ToDateTime和更多。

See this MSDNexample:

请参阅此MSDN示例:

Dim dateValue As Date
Dim dateString As String = "2/16/2008" 

Try
  dateValue = Date.Parse(dateString)
  Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue)
Catch e As FormatException
  Console.WriteLine("Unable to convert '{0}'.", dateString)
End Try