adolf garlic
adolf garlic

Reputation: 3096

Why doesn't CDate(integer) work where integer has format of YYYYMMDD?

Why doesn't CDate(integer) work where integer has format of YYYYMMDD ?

and why won't this stupid site let me submit such a short question when I have nothing else to add except some waffle at the end

1 > 2 blah etc

Upvotes: 1

Views: 476

Answers (2)

Steve Wortham
Steve Wortham

Reputation: 22240

What Ahmad said. In addition, you can use the TryParseExact function in your particular example...

Dim Value As Integer = 20120314

Dim MyDate As DateTime
If DateTime.TryParseExact(Value.ToString(), "yyyyMMdd", CultureInfo.CurrentCulture, DateTimeStyles.None, MyDate) Then
    'Do what you want with MyDate.  For example...
    Console.WriteLine(MyDate.ToShortDateString())
End If

The beauty part of all the TryParse and TryParseExact functions is they simply return a Boolean value indicating that the parsing passed or failed. They do not throw an exception.

Upvotes: 4

Ahmad Mageed
Ahmad Mageed

Reputation: 96507

Integers aren't supported, per MSDN:

Use the IsDate function to determine if a value can be converted to a date and time. CDate recognizes date literals and time literals but not numeric values.

This returns false:

Dim isValid = IsDate("20120314") ' false

You can use a valid date representation as a string, however. Example:

Dim result = CDate(DateTime.Now.ToString("yyyy-MM-dd"))

Upvotes: 5

Related Questions