In this blog, we are going to
parse the string to specific Date Time data Type.
Usage:
DateTime
a3 = TryParseDateTime("31/5/2012",
DateTime.MinValue);//TRUE
DateTime b3 = TryParseDateTime("05/32/2012",
DateTime.MinValue);//FALSE
Response.Write(string.Format("A:{0},B:{1}", a3.ToString("dd/MM/yyyy"),
b3.ToString("dd/MM/yyyy")) + "<br/>");
Output:
A:31/05/2012,B:01/01/0001
Best to use if there is uncertain about the
input string.
///
<summary>
///
Note it takes your System dateTime format like d/M/yyyy etc.
/// It
wont throw error. Instead it gives the ifFail value if error occurs
///
</summary>
public
DateTime TryParseDateTime(string
input, DateTime ifFail)
{
DateTime output;
if (DateTime.TryParse(input,
out output))
{
output = output;
}
else
{
output = ifFail;
}
return output;
}
///
<summary>
/// Parses the string
as DateTime. But if datetime string is invalid, then it throws error
///
</summary>
public
DateTime ParseDateTime(string
input)
{
return
DateTime.Parse(input);
}
Thanks for reading this
article. Have a nice day.