Use DateTime.TryParse method.
This is how it is done:
DateTime dateTime;
DateTime.TryParse(strDateTime, out dateTime);
The coolest part is TryParse will return
True
if the parsing is successful and return
False
if the parsing fail. You can either use the statement in a
if
condition.
Update 1:
shan1395 wrote:
DateTime strDateTime = System.Convert.ToDateTime(item.StartDate);
This code is one of the ways to convert string to DateTime. It is not required to use TryParse if you use Convert.ToDateTime
Convert.ToDateTime will fail and throw exception if the string is empty. But TryParse will not throw exception.
Solution 1:
DateTime dateTime = System.Convert.ToDateTime(item.StartDate);
or
Solution 2:
DateTime dateTime;
DateTime.TryParse(item.StartDate, out dateTime);
Mark it as answer if it is helpful