New post has been published on Date format conversion
If you are tired of Date format conversion error because you have to take care of user locale settings and based on that you have to pasre the
date to desired format using DateTime.Parse or Convert.ToDateTime methods. Still you can get error of “input string was not in correct format”
so there is a way around to this problem. Below is the method which takes the source date, source format and returns you the destination format
as specified in the parameters.
Have a look at that:
public static string GetFormattedDate(String SourceDate, string SourceDateFormat, string ReturnFormat)
string[] Params = new string[3];
string sDate = "";
string sMonth = "";
string sYear = "";
string DateSeparator = "/";
if (SourceDate.Length > 1)
if (SourceDate.Length > 9)
SourceDate = SourceDate.Substring(0, 10);
else if (SourceDate.Length == 9)
SourceDate = SourceDate.Substring(0, 9);
SourceDate = SourceDate.Replace("-", "/");
Params = SourceDate.ToString().Split(DateSeparator.ToCharArray());
if (SourceDateFormat == "dd/mm/yyyy")
if (Params[0].Length == 1)
sDate = "0" + Params[0].ToString();
else
sDate = Params[0];
if (Params[1].Length == 1)
sMonth = "0" + Params[1].ToString();
else
sMonth = Params[1];
if (Params[2].Length == 1)
sYear = "0" + Params[2].ToString();
else
sYear = Params[2].Substring(0, 4);
else if (SourceDateFormat == "mm/dd/yyyy")
if (Params[1].Length == 1)
sDate = "0" + Params[1].ToString();
else
sDate = Params[1];
if (Params[0].Length == 1)
sMonth = "0" + Params[0].ToString();
else
sMonth = Params[0];
if (Params[2].Length == 1)
sYear = "0" + Params[2].ToString();
else
sYear = Params[2].Substring(0, 4);
switch (ReturnFormat)
case "dd/mm/yyyy":
return sDate + DateSeparator + sMonth + DateSeparator + sYear;
case "mm/dd/yyyy":
return sMonth + DateSeparator + sDate + DateSeparator + sYear;
default:
return "";
else
return "";
Basically what it does is, it splits the date and manually formats the date accodring to the desired format.
So you can try it like this:
DateTime dtJoinDate = Convert.ToDateTime(GetFormattedDate(txtJoinDate.Text, "dd/mm/yyyy", "mm/dd/yyyy"));
Enjoy…
No comments:
Post a Comment